0

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?

1 Answer 1

2

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>();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation, that makes sense now.
Could I request you to look at a different piece of code and get your opinion ?
@Philo if it's related to this question, just edit your original question. Otherwise, best to open a new question and ask there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.