foxx1337
foxx1337

Reputation: 2026

The type of Dictionary initializers

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)'

Upvotes: 3

Views: 191

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

That's not possible. The dictionary initializer is syntactic sugar. So your code

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

Is actually translated to something like:

var tmp = new Dictionary<string, int>();
tmp.Add("12", 12);
tmp.Add("13", 13};
var a = tmp;

So the elements are used as argument for Add. Even if Fifteen() would return a KeyValuePair<string,int> the compiler would still be missing an appropriate Add method.

(But as Servy showed, you can provide an extension Add method that does the trick)

Upvotes: 2

Servy
Servy

Reputation: 203835

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.

Upvotes: 14

Related Questions