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 class Node{
public IList<Node> Children {get; protected set;}
public Node(){
Children = new ObservableList<Node>();
}
}
... in my code somewhere...
var node = new Node {Children.Add(new Node())};
(not a great example, but I hope this gets the idea across)...
UPDATE
OK sorry I need to be clearer. I didn't write this Node
class, and I cannot change it. I am asking if there is a c# language concept that will allow me to add to the readonly collection in the parameterless constructor in the second snippet, assuming the Node
class is not changeable.
If you have a property of type List that is
get
only, that only means you can't set that property, you can still add things to the list.You could however expose an
IEnumerable
property instead and have a constructor that takes a list(or anotherIEnumerable
more likely).Property initializers do not work since the compiler will just rewrite them to regular property assignments.
I'd do this:
if you can't change the
Node
class, I suggest writing a helper class similar to this:You can add a backing field to the "Children" property, then just populate the backing field during construction.
Like so
Then you can do this
Try this. It is definitely possible to add elements on construction
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
Hence such a class cannot offer the immutability you desire. I think the best solution to your problem would be to do this
or if you do not like the deferred execution of IEnumerable: