How does assigning default values when creating an instance work? [Answered]

I'm not sure how to ask this question. I also can't for the life of me remember what this style of instance creating is called, otherwise I would just look it up.
public interface IData
{
int Value { get; set; }
}
public class Data : IData
{
public int Value { get; set; }
}

public class Container
{
public IData DataSlot { get; set; }
}

// In some method...

var container = new Container()
{
// How does this work? DataSlot is a interface.
DataSlot = { Value = 5 }
}
public interface IData
{
int Value { get; set; }
}
public class Data : IData
{
public int Value { get; set; }
}

public class Container
{
public IData DataSlot { get; set; }
}

// In some method...

var container = new Container()
{
// How does this work? DataSlot is a interface.
DataSlot = { Value = 5 }
}
7 Replies
Saber
Saber3y ago
it "works" as in it compiles, but it doesn't actually work
333fred
333fred3y ago
That is called a nested member initializer, and the key thing is that it's not creating an instance of IData Here's what the code looks like, long form:
var tmp = new Container();
tmp.DataSlot.Value = 5;
var container = tmp;
var tmp = new Container();
tmp.DataSlot.Value = 5;
var container = tmp;
So, in this case, what will actually happen is you get a null reference exception
MechWarrior99
MechWarrior99OP3y ago
Oh, looks like it does work if DataSlot is assigned in the constructor of Container
333fred
333fred3y ago
Correct. Because it's just calling DataSlot.Value
MechWarrior99
MechWarrior99OP3y ago
Interesting, I think I get it now. I think I was confusing it with it having the new word DataSlot = new DataSlot() { .. }. Thanks for the help!
333fred
333fred3y ago
np
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?