3

This morning I encountered an interesting situation in an application I'm building. Even though I've resolved this in another way, I'm interested in finding out what the answer would be.

Lets say we have the following situation:

public class SomeDependency
{
    public string SomeThing { get; set; }
}

public class SomeClass
{
    public SomeDependency Dependency { get; }

    public SomeClass() : this(new SomeDependency) { }

    public SomeClass(SomeDependency dependency) 
    {
        Dependency = dependency;
    }
}

Right now there are 2 ways of initializing this class:
We could just say:

var x = new SomeClass();

That of course would give us the expected situation. But what if we do this:

var x = new SomeClass 
{
    Dependency = new SomeDependency { SomeThing = "some random string" }
};

We use the parameterless constructor in the latter situation but we do give Dependency a value via object initializer, hence my question:

Will Dependency be overwritten by the the this(new SomeDependency()) call?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Goos van den Bekerom
  • 1,475
  • 3
  • 20
  • 32
  • *Will Dependency be overwritten by the the this(new SomeDependency()) call?* The opposite. First the constructor runs completely, then the field/property initialization is done (`Dependency = `). Object initializer is pure synctactic sugar. It is done *after* the `new SomeClass` has returned the new object. – xanatos Apr 13 '17 at 07:32

1 Answers1

2

Your code is actually converted by the compiler to this:

var x = new SomeClass();
x.Dependency = new SomeDependency { SomeThing = "some random string" };

So no, the constructor will not override the value you set for Dependency. Instead it will change the value defaulted in the constructor on the second line.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325