What benefits does dictionary initializers add over collection initializers?

前端 未结 3 930
深忆病人
深忆病人 2020-12-03 16:43

In a recent past there has been a lot of talk about whats new in C# 6.0
One of the most talked about feature is using Dictionary initializers in C# 6.0

3条回答
  •  北海茫月
    2020-12-03 17:22

    Just to stress the most important difference, dictionary initializer calls the indexer, and hence it performs an update when duplicate keys are encountered, whereas collection initializer calls the Add method which will throw.

    To briefly summarize the differences in general:

    1. Collection initializer calls Add method (for IEnumerables) where as dictionary initializer calls indexer. This has the Add vs Update semantic differences for dictionaries.

    2. Dictionary initializer is technically an object initializer, hence can be mixed with initializing other properties. For e.g.:

      new Dictionary
      {
          [1] = "Pankaj",
          [2] = "Pankaj",
          [3] = "Pankaj",
          Capacity = 100,
      };
      

      but not

      new Dictionary() 
      {
          { 1,"Pankaj" },
          { 2,"Pankaj" },
          { 3,"Pankaj" },
          Capacity = 100, // wont compile
      };
      
    3. Being just an object initializer, indexed initializer can be used for any class with an indexer, whereas collection initializer can be used only for IEnumerables, which should be obvious anyway.

    4. Collection initializer can be enhanced with custom Add extension methods, whereas ditionary initializer can't be (no extension indexer in C# yet).

    5. Dictionary initializer maybe subjectively slightly more readable when it comes to initializing a dictionary :)

    6. Dictionary initializer is C# 6.0 feature whereas collection initializer is available from C# 3.0 onwards.

提交回复
热议问题