c# - What benefits does dictionary initializers add over collection initializers? -


in recent past there has been lot of talk whats new in c# 6.0
1 of talked feature using dictionary initializers in c# 6.0
wait have been using collection initializers initialize collections , can initialize dictionary in .net 4.0 , .net 4.5 (don't know old version) like

dictionary<int, string> mydict = new dictionary<int, string>() {     { 1,"pankaj"},     { 2,"pankaj"},     { 3,"pankaj"} }; 

so there new in c# 6.0, dictionary initializer talking in c# 6.0

while could initialize dictionary collection initializers, it's quite cumbersome. that's supposed syntactic sugar.

dictionary initializers cleaner:

var mydict = new dictionary<int, string> {     [1] = "pankaj",     [2] = "pankaj",     [3] = "pankaj" }; 

more importantly these initializers aren't dictionaries, can used any object supporting indexer, example list<t>:

var array = new[] { 1, 2, 3 }; var list = new list<int>(array) { [1] = 5 }; foreach (var item in list) {     console.writeline(item); } 

output:

1 5 3 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -