Is is possible to combine a List initializer and object initializer at the same time? Given the following class definition:
class MyList : List<int>
{
public string Text { get; set; }
}
// we can do this
var obj1 = new MyList() { Text="Hello" };
// we can also do that
var obj2 = new MyList() { 1, 2, 3 };
// but this one doesn't compile
//var obj3 = new MyList() { Text="Hello", 1, 2, 3 };
Is this by design or is it just a bug or missing feature of the c# compiler?
No, looking at the definitions from section 7.6.10 of the C# spec, an
object-or-collection-initializer
expression is either anobject-initializer
or acollection-initializer
.An
object-initializer
is composed of multiplemember-initializer
s, each of which is of the forminitializer = initializer-value
whereas acollection-initializer
is composed of multipleelement-initializer
s, each of which is anon-assigment-expression
.So it looks like it's by design - possibly for the sake of simplicity. I can't say I've ever wanted to do this, to be honest. (I usually wouldn't derive from
List<int>
to start with - I'd compose it instead.) I would really hate to see:EDIT: If you really, really want to enable this, you could put this in the class:
at which point you could write:
No, it's a not a bug. It is by design of the language.
When you write
this is effectively translated by the compiler to
When you write
this is effectively translated by the compiler to
Note that in the first case you are using an object initializer, but in the second case you are using a collection initializer. There is no such thing as an object-and-collection intializer. You are either initializing the properties of your object, or you are initializing the collection. You can not do both, this is by design.
Also, you shouldn't derive from
List<T>
. See: Inheriting List<T> to implement collections a bad idea?If you want to get something like this functionality, consider making a constructor argument: