Reputation: 1989
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?
Upvotes: 0
Views: 105
Reputation: 9593
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>();
}
Upvotes: 2