Value Tuples for passing Lists of Key-Value Pairs in C# 7

alistairjevans profile image Alistair Evans Originally published at alistairevans.co.uk on ・2 min read

Prior to C# 7, I have many, many times found myself needing to pass a hard-coded list of key-value pairs to a method, and I’ve had to do it painfully:

We can make this marginally better with a factory function:

Then we can swap the list with an array to improve it a little more:

Finally, we can use ‘params’ on the method so we don’t need to declare an array on the caller:

Okay, so it’s not too bad, but we still have that factory function which I’m not a fan of.

Value Tuples

Briefly, Value Tuples let you do things like this:

You get a small value type containing your two values, that you can declare inline, and access the individual values in the result.

You don’t just have to use these in return types, you can use them anywhere a type definition could be used.

I’ve generally been a little reticent to use this new-ish feature too heavily, because I’m worried about people using them where they should actually be defining types.

That being said…

Making Our Parameters Nicer

In C# 7, now we get to pass those key-value lists the nice way:

Look at that! No factory function required, we can simply pass in the pairs, just as I’ve wanted to be able to do for years, and it’s super readable.

Just define the array type of your params argument as the tuple you want, and away you go!

I’m still a little wary of Value Tuples generally, but this is definitely a lovely use case for them.

Posted on by:

alistairjevans profile

Alistair Evans


Software developer that likes to dabble.


markdown guide

That was a great idéa thanks, that use-case was spot on for something I am working on!