Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining List initializer and object initializer

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?

like image 258
codymanix Avatar asked Jun 06 '11 15:06

codymanix


People also ask

What is object initializer?

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.

How do you initialize a list of objects in C#?

You can initialize a list by using List<string> name = new List<string> and use curly brackets to define its values like {new Element() {Id = 1, Name = "first"} by populating objects of the Element class.

What is collection initializer?

C# 3.0 (. NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor.

How do you initialize an object in C++?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.


1 Answers

No, looking at the definitions from section 7.6.10 of the C# spec, an object-or-collection-initializer expression is either an object-initializer or a collection-initializer.

An object-initializer is composed of multiple member-initializers, each of which is of the form initializer = initializer-value whereas a collection-initializer is composed of multiple element-initializers, each of which is a non-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:

var obj3 = new MyList { 1, 2, Text = "Hello", 3, 4 };

EDIT: If you really, really want to enable this, you could put this in the class:

class MyList : List<int>
{
    public string Text { get; set; }
    public MyList Values { get { return this; } }
}

at which point you could write:

var obj3 = new MyList { Text = "Hello", Values = { 1, 2, 3, 4 } };
like image 89
Jon Skeet Avatar answered Oct 19 '22 16:10

Jon Skeet