简体   繁体   中英

C# initializing List Collection

I have always initialized a collection as such:-

List<Type> name = new List<Type>();

But today I saw something like this:-

var variablename = new sMonth{
    x = foo;
    name = new List<Type>()
};

Is that even possible? and what is the difference between the two ways?

Yes, your second snippet is an example of object initialization .

Assuming your sMonth object contains a property of type List<Type> , you can initialize the object at the point you create the outer object:

var variablename = new sMonth{
    x = foo,
    name = new List<Type>()
};

Note the comma between items.

Additionally, since you're not assigning anything to name you could use the sMonth constructor to initialize the collection for you:

public sMonth()
{
    name = new List<Type>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM