Jaouad Ouahi Jaouad Ouahi - 1 month ago 8
C# Question

C# Class without explicit constructor and read only property

Can someone explain me how this code works ?

public class Person
{
readonly List<Person> _children = new List<Person>();
public IList<Person> Children
{
get { return _children; }
}

public string Name { get; set; }
}

public static Person GetFamilyTree()
{
return new Person
{
Name = "David Weatherbeam",
Children =
{
new Person
{
Name="Alberto Weatherbeam",
Children=
{
new Person
{
Name="Jenny van Machoqueen",
Children=
{
new Person
{
Name="Nick van Machoqueen",
},
new Person
{
Name="Matilda Porcupinicus",
}
}
}
}
}
}
};
}


The 'Children' property is 'read-only' (as it has no setter).
The 'GetFamilyTree' function seems to use an implicit initializer which is fine for 'Name' property as it can be accessed outside 'Person' but how 'Children' property can be assigned in this function?

Thank you for your explanations.
Cheers.

Answer

This somewhat confusing object initializer syntax retrieves the collection with the get accessor and uses the public Add method on the collection. It works because the compile-time type of the property IList<Person> has (inherits) a public Add method with a compatible signature (takes in a Person argument).

Comments