Using key-value pairs as parameters

Wim ten Brink picture Wim ten Brink · Sep 1, 2009 · Viewed 13.2k times · Source

Simple. If I use:

public void Add(params int[] values)

Then I can use this as:

Add(1, 2, 3, 4);

But now I'm dealing with key-value pairs! I have a KeyValue class to link an integer to a string value. So I start with:

public void Add(params KeyValue[] values)

But I can't use this:

Add(1, "A", 2, "B", 3, "C", 4, "D");

Instead, I'm forced to use:

Add(new KeyValue(1, "A"), new KeyValue(2, "B"), new KeyValue(3, "C"), new KeyValue(4, "D"));

Ewww... Already I dislike this...

So, right now I use the Add function without the params modifier and just pass a pre-defined array to this function. Since it's just used for a quick initialization for a test, I'm not too much troubled about needing this additional code, although I want to keep the code simple to read. I would love to know a trick to use the method I can't use but is there any way to do this without using the "new KeyValue()" construction?

Answer

Marc Gravell picture Marc Gravell · Sep 1, 2009

If you accepted an IDictionary<int,string>, you could presumably use (in C# 3.0, at least):

Add(new Dictionary<int,string> {
     {1, "A"}, {2, "B"}, {3, "C"}, {4, "D"}
});

Any use?

Example Add:

static void Add(IDictionary<int, string> data) {
    foreach (var pair in data) {
        Console.WriteLine(pair.Key + " = " + pair.Value);
    }
}