The type of Dictionary initializers

  • A+
Category:Languages

I have this code:

class Program {     static void Main(string[] args)     {         var a = new Dictionary<string, int>()         {             { "12", 12 },             { "13", 13 },         };     }      static object Fifteen()     {         //return new object[] { "15", 15 };         return new {key = "15", value = 15};     } } 

How do I write Fifteen so that I can add it to the initializer?

I want this, that compiles:

        var a = new Dictionary<string, int>()         {             { "12", 12 },             { "13", 13 },             Fifteen()         }; 

L.E. the compilation error is: error CS7036: There is no argument given that corresponds to the required formal parameter 'value' of 'Dictionary<string, int>.Add(string, int)'


You'll want to change your Fifteen method so that it returns a KeyValuePair, rather than an object, so that the callers of the method can access the data you're providing (anonymous types should only be used when they're consumed in the same method that they're created):

static KeyValuePair<string, int> Fifteen() {     return new KeyValuePair<string, int>("15", 15); } 

And then you'll need to add an extension method to Dictionary so that it has an Add method that accepts a KeyValuePair rather than two arguments:

public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, KeyValuePair<TKey, TValue> pair) {     dictionary.Add(pair.Key, pair.Value); } 

After which your stated code compiles and runs just fine.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: