The code you've provided isn't a class initializer or for anonymous types. The kind of class that this works for is a collection, but it can be defined minimally as this:
public class MyClass : IEnumerable<int>
{
private List<int> _list = new List<int>();
public void Add(int x)
{
Console.WriteLine(x);
_list.Add(x);
}
public IEnumerator<int> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
}
Now you can run the code from your question:
var myObject = new MyClass { 42 };
You will get 42
written to the console.
The syntax is a collection initializer syntax and it basically requires the class to implement IEnumerable<T>
and have a public Add(T value)
method.
You can then add multiple values too:
var myObject = new MyClass { 42, 43, 44 };