To achieve the implementation of the initialization syntax you can use collection initializers on your object but only if that object implements IEnumerable
.
If the object implements IEnumerable
then you can add an Add
method that will be called when you initialize an object. As an example here is how you might initizlize entries in a simple matrix class:
public class Matrix : IEnumerable
{
public int[,] _data = new int[3,3];
public void Add(int x, int y, int value)
{
_data[x,y] = value;
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
I can initialize it like this:
var myObject = new Matrix() {
{1,2,3},
{0,0,10}
};
This will be the equivalent of writing:
var myObject = new Matrix();
myObject.Add(1,2,3);
myObject.Add(0,0,10);
Custom Collection Initializers is a question about custom collection initializers which, amongst other things, has a quote from the spec about them.
As mentioned earlier this only works for objects that implement IEnumerable
. As demonstrated above you don't have to have a useful implementation of IEnumerable
for this to work but I would discourage you from making something IEnumerable
to get this behaviour if the object isn't really an IEnumerable
.
>`
– MethodMan Dec 10 '17 at 00:36