Wield the Power of Generic Type Inference

by KodefuGuru 11. December 2009 17:35

One class that bothers me in the .NET Framework is KeyValuePair<K, V>. To create one these, you must explicitly declare the generic types being used.

var pair = new KeyValuePair<int, string>(42, "The Answer");

The .NET Framework support generic type inference, so why did the designer of the KeyValuePair<K, V> class decide it would be good idea to force us to write out the types? Take a look at another type of pair from .NET 4: the 2-valued Tuple.

var pair = new Tuple<int, string>(42, "The Answer");

Yes, you can write it just like the KeyValuePair, but that doesn’t solve our problem. Let’s try that another way.

var pair = Tuple.Create(42, "The Answer");      

That’s better. The designer of the Tuple class was nice enough to give us a factory method. The factory method still has the generic types on it, but it can infer what those types are from the parameters passed into the method. I really don’t like being forced to declare generic definitions everywhere (could you imagine how horrible LINQ would be if you had to do that), so let’s fix KeyValuePair.

public static class KeyValuePair
{
    public static KeyValuePair<K, V> Create<K, V>(K key, V value)
    {
        return new KeyValuePair<K, V>(key, value);
    }
}

That was an easy helper method to create. Let’s take a look at how to use it.

var pair = KeyValuePair.Create(42, "The Answer");   

The usage is identical to Tuple’s pair factory method.

Types are inferred on arguments passed into a generic method. You can take advantage of this feature to reduce typing and write cleaner code. At the very least, you can provide a factory method.

Tags: , , ,

Kodefu

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010