Search code examples
c#constructorproperties

What is the Difference Between Constructors and Object Construction?


I was trying to understand Auto-Implemented Properties by reading the Microsoft Documentation.) when it mentioned three ways to modify Auto Properties near the bottom of the page:

  • Using get; only,
  • Using get; init;, and
  • Using get; private set;.

According to the document, the first implementation is used to make the property immutable everywhere except the constructor. The second is immutable everywhere, except during object construction only. And the third is when you want the property to be immutable to all consumers.

get; private set; is clear where that would be implemented, but my issue comes with the first and second cases. What is the difference between using constructors and "object construction?" I thought they were interchangeable. But here, from what I understand, the document is implying that they are different. Is there something I am missing? Or am I misunderstanding?

I tried googling it and searched in stack overflow. I saw many posts discussing similar issues regarding the difference between get; and get; init;, but that was already clear to me. I couldn't find my exact question being answered.


Solution

  • For a quick example of the difference:

    class C
    {
        public int Prop1 { get; } = 2;
        public int Prop2 { get; init; } = 4;
    
        // constructor
        public C()
        {
            // Prop1 is only assignable here
            Prop1 = 6;
            // Prop2 is assignable here, but also in the "object initializer"
            Prop2 = 8;
        }
    }
    
    // the stuff inside the {} is what the docs are referring to
    // as "object initializer"
    var c = new C()
    {
        // this next line would be an error
        // Prop1 = 10,
    
        // setting Prop2 works fine,
        // this also overwrites what was set in the constructor 
        Prop2 = 10
    }
    

    Prop2 cannot be set again after those {} end, which is what differentiates init from set.