c# - anonymous object initialisation with single variable -
i found have found such line:
var myobject = new myclass { 42 };
and know if possible perform such operation. documentation says ,,you must use object initializer if you're defining anonymous type" obvious cant find alone integer in braces.
the code you've provided isn't class initializer or anonymous types. kind of class works collection, can defined minimally 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 can run code question:
var myobject = new myclass { 42 };
you 42
written console.
the syntax collection initializer syntax , requires class implement ienumerable<t>
, have public add(t value)
method.
you can add multiple values too:
var myobject = new myclass { 42, 43, 44 };
Comments
Post a Comment