user2999425
user2999425

Reputation: 125

anonymous object initialisation with single variable

I found have found such a line:

var myObject = new MyClass { 42 };  

And I would like to know if it is possible to perform such operation. Documentation says that ,,You must use an object initializer if you're defining an anonymous type" so this is obvious but I cant find anything about alone integer in braces.

Upvotes: 2

Views: 243

Answers (2)

Enigmativity
Enigmativity

Reputation: 117134

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 }; 

Upvotes: 3

Steve Cooper
Steve Cooper

Reputation: 21490

No, but you can either call a constructor;

new MyClass(42)

if one is defined, or set any settable properties like this;

new MyClass { MeaningOfLife=42 };

Upvotes: 7

Related Questions