StayOnTarget
StayOnTarget

Reputation: 13008

Initializer syntax vs. parameterless constructor syntax

There are two alternative styles of instantiating a new empty "list" -style object:

var list = new SomeListType<int>();

or

var list = new SomeListType<int> { };

The first relies on allowing the basic constructor to setup the object, the second would seem to also implicitly rely on the constructor, but also specifies an empty initializer list.

(The intializer list being left empty on purpose, say if it seemed to be more readable or clearer in some context.)

Is there any practical or functional difference between these two approaches?

(Note -- SomeListType could be anything that can be constructed like this - such as a standard List<T> or some custom class. Using int just for example).

Upvotes: 2

Views: 86

Answers (2)

dymanoid
dymanoid

Reputation: 15197

Even the generated IL code will be the same for both options:

newobj instance void class Namespace.SomeListType`1<int32>::.ctor() 

So there is no functional difference at all.

Upvotes: 2

Sefe
Sefe

Reputation: 14007

The two lines you have written will compile the same. The difference is that in the second version you can initialize the list by adding items in the curly braces (provided your lists implements the ICollection<T> interface or provides a respective Add method:

var list = new SomeListType<int> { 1, 2, 3, 4 };

Upvotes: 1

Related Questions