3

C# I am using a KeyValuePair as a key in my main KeyValuePair. Here is my problem:

If I have "KeyValuePair", the declaration would be as following:

KeyValuePair<String,String> varName = new KeyValuePair<String,String>("String 1","String 2");

How do I declare it if i have the following:

KeyValuePair<KeyValuePair<String,String>,int>

I got so lost in the syntax here. Please help me out!

Thank you!

1 Answers1

4

You pretty much have it, but it's easiest to split it into two initialisations.

Firstly, initialise the KeyValuePair<string, string> and then use that along with an int to initalise the KeyValuePair<KeyValuePair<string, string>, int>:

var pair = new KeyValuePair<string, string>("string 1", "string 2");
var varName = new KeyValuePair<KeyValuePair<string, string>, int>(pair, 10);

You can simplify this considerably if you write a helper method like so:

public static KeyValuePair<T1, T2> MakeKeyValuePair<T1, T2>(T1 key, T2 value)
{
    return new KeyValuePair<T1, T2>(key, value);
}

Using that, you can do the following instead:

var pair    = MakeKeyValuePair("string 1", "string 2");
var varName = MakeKeyValuePair(pair, 10);

This is much easier to follow, and you don't need to explicitly specify the types.

Or if you prefer (I personally don't prefer this):

var varName = MakeKeyValuePair(MakeKeyValuePair("string 1", "string 2"), 10);

But if you really want to do it the hard way:

var varName = new KeyValuePair<KeyValuePair<string, string>, int>(
    new KeyValuePair<string, string>("string 1", "string 2"), 
    10);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276