Sunday, February 8, 2015

Dictionary Initializer in C# 6.0

 

After C# 3.0 is released we had the ability of initializing lists and dictionaries using following syntax.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.             {
  3.                 { "admin",new User("Sammani") },
  4.                   { "Guest",new User("Hemal") },
  5.             };

Here we add the key value pairs inside the “{ }”. In c# 6.0 it has a new syntax as follows which gives more look like working with key value pairs.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.           {
  3.               [ "admin"]=new User("Sammani") ,
  4.                ["Guest"]=new User("Hemal")
  5.           };

you can the number of characters are almost same in both the syntax but in c# 6.0 syntax looks more a like key value pair.

This is another syntax sugar added in c# 6.0.

Happy Coding

No comments :

Post a Comment