Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I initialize a List like an array in C#?

People also ask

Why is a list better than an array?

The list is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. List occupies much more memory as every node defined the List has its own memory set whereas Arrays are memory-efficient data structure.

Do arrays need to be initialized in C?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero. If an array is to be completely initialized, the dimension of the array is not required.

Can you initialize an empty array in C?

Technically you can't make an array empty. An array will have a fixed size that you can not change. If you want to reset the values in the array, either copy from another array with default values, or loop over the array and reset each value.


This is part of the collection initializer syntax in .NET. You can use this syntax on any collection you create as long as:

  • It implements IEnumerable (preferably IEnumerable<T>)

  • It has a method named Add(...)

What happens is the default constructor is called, and then Add(...) is called for each member of the initializer.

Thus, these two blocks are roughly identical:

List<int> a = new List<int> { 1, 2, 3 };

And

List<int> temp = new List<int>();
temp.Add(1);
temp.Add(2);
temp.Add(3);
List<int> a = temp;

You can call an alternate constructor if you want, for example to prevent over-sizing the List<T> during growing, etc:

// Notice, calls the List constructor that takes an int arg
// for initial capacity, then Add()'s three items.
List<int> a = new List<int>(3) { 1, 2, 3, }

Note that the Add() method need not take a single item, for example the Add() method for Dictionary<TKey, TValue> takes two items:

var grades = new Dictionary<string, int>
    {
        { "Suzy", 100 },
        { "David", 98 },
        { "Karen", 73 }
    };

Is roughly identical to:

var temp = new Dictionary<string, int>();
temp.Add("Suzy", 100);
temp.Add("David", 98);
temp.Add("Karen", 73);
var grades = temp;

So, to add this to your own class, all you need do, as mentioned, is implement IEnumerable (again, preferably IEnumerable<T>) and create one or more Add() methods:

public class SomeCollection<T> : IEnumerable<T>
{
    // implement Add() methods appropriate for your collection
    public void Add(T item)
    {
        // your add logic    
    }

    // implement your enumerators for IEnumerable<T> (and IEnumerable)
    public IEnumerator<T> GetEnumerator()
    {
        // your implementation
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Then you can use it just like the BCL collections do:

public class MyProgram
{
    private SomeCollection<int> _myCollection = new SomeCollection<int> { 13, 5, 7 };    

    // ...
}

(For more information, see the MSDN)


It is so called syntactic sugar.

List<T> is the "simple" class, but compiler gives a special treatment to it in order to make your life easier.

This one is so called collection initializer. You need to implement IEnumerable<T> and Add method.


According to the C# Version 3.0 Specification "The collection object to which a collection initializer is applied must be of a type that implements System.Collections.Generic.ICollection for exactly one T."

However, this information appears to be inaccurate as of this writing; see Eric Lippert's clarification in the comments below.


It works thanks to collection initializers which basically require the collection to implement an Add method and that will do the work for you.