Is there a c# language construct that will allow me to add items to a readonly collection property in a constructor? I want to do something like this:
public cl
To use the collection initializer syntax from you second code snippet your Node class must implement IEnumerable and have a public method with the signature
void Add(Node child)
Hence such a class cannot offer the immutability you desire. I think the best solution to your problem would be to do this
public class Node
{
public readonly IEnumerable Children;
public Node(IEnumerable children)
{
Children = children;
}
}
or if you do not like the deferred execution of IEnumerable:
public class Node
{
public readonly ReadOnlyCollection Children;
public Node(IEnumerable children)
{
Children = new ReadOnlyCollection(children);
}
}