C# 3.0 Features - Part 3.3 Collection Initializers

Apr
24
2011
In Categories: .NET | CLR
Tags | |

You can see part 0 here, part 1 here and part 2 here

This is also feature that helps the developer to be more productive. Let's see how we can use it.

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

As you can see, we just fill in the numbers inside the list, Using objects will be like this:

    1 Dictionary<string, string> foo = new Dictionary<string, string>()

    2 {

    3     { "key1", "value1" },

    4     { "key2", "value2" }

    5 };

Let's see what happened behind the scenes, Just to realize the value of that code.

    1         List<int> <>g__initLocal1 = new List<int>();

    2         <>g__initLocal1.Add(2);

    3         <>g__initLocal1.Add(4);

    4         <>g__initLocal1.Add(6);

    5         <>g__initLocal1.Add(8);

    6          List<int> Digits = <>g__initLocal1;

And for the Dictionary object

    1         Dictionary<string, string> <>g__initLocal2 = new Dictionary<string, string> ();

    2         <>g__initLocal2.Add("key1", "value1");

    3         <>g__initLocal2.Add("key2", "value2");

    4         Dictionary<string, string> foo = <>g__initLocal2;

As you can see the complier did what we should have done using the add method in each line. This feature helps us to be more productive and make the code more readable.

Comments

trackback
Technical Architect blog
4/24/2011 2:38:54 AM Permalink

C# 3.0 Features - Part 3.4 Implicit Typing

C# 3.0 Features - Part 3.4 Implicit Typing

Comments are closed