Key-Value-Pair Utility - Make Helsinki

Key-Value-Pair Utility

by: Davor Skontra
  •   Development •  30.3.2020   •  2 minute read

Utilitarian Life, Chapter 2

This is the second part in Utilitarian Life; a series of articles where programmers from Make Helsinki discuss tools and utilities we have written and reuse often. The first part was about a Unity Specific utility called VectorUtilities. If you are a Unity programmer I definitely recommend checking it out.

Here we will talk about the KeyValuePairUtility. While it is pretty useful in Unity, it is equally neat for other project using C# 7.0 or higher.

So, about the utility…

Do you remember the last time you iterated through a dictionary? It might have looked something like this?

This is alright, but I really hate retrieving Key and Value like that. You could shorten this by using them straight in the GivePats method call like this:

GivePats(personAndAmount.Key, personAndAmount.Value)

But this would sacrifice some readability. I don’t think it’s an ideal solution.

C# 7.0  introduced the capability for object deconstruction. This works great for your own types; But did you know you can also do it with native types by writing extension methods?

When iterating through a dictionary, the iterated-on type is KeyValuePair. Like seen above, it has properties for Key and Value which fetch keys and values respectively.

Now look at his example.

I at least find this easier to read and obviously there is also less typing involved.

Unfortunately, it’s not possible to do this natively.

Fortunately, it’s not hard to implement yourself (Or just grab the source from here, everything in that repository is MIT licensed).

There. All that you need is to have this extension method in your project and the compiler will know how to deconstruct the KeyValuePair items.

I think it’s pretty neat.

Go have fun with this! Hopefully you’ll find it as awesome as I did. And if you have some comments, drop them here; I’m curious to hear what you think.

Leave a Reply

Your email address will not be published. Required fields are marked *