C#: Type Inferences For Generic Methods

by Jon Davis 17. March 2009 12:40

C# 3.0 has a cool feature I didn’t realize existed until now. I already knew that you can create generic methods, like so:

protected static T CaseInsensitiveFindValue<T>(Dictionary<string, T> dic, string key)
    if (dic.ContainsKey(key)) return dic[key];
    foreach (var kvp in dic)
        if (kvp.Key.ToLower() == key.ToLower()) return kvp.Value;
    return default(T);

That goes back to 2.0. What I didn’t realize until now was that when you invoke this method, you don’t have to pass the type in as a type argument for T. The type can be inferred!

var value = CaseInsensitiveFindValue(myDictionary, myKey);

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


C# | Software Development

Add comment

(Will show your Gravatar icon)  

  Country flag

  • Comment
  • Preview


Powered by BlogEngine.NET
Theme by Mads Kristensen

About the author

Jon Davis (aka "stimpy77") has been a programmer, developer, and consultant for web and Windows software solutions professionally since 1997, with experience ranging from OS and hardware support to DHTML programming to IIS/ASP web apps to Java network programming to Visual Basic applications to C# desktop apps.
Software in all forms is also his sole hobby, whether playing PC games or tinkering with programming them. "I was playing Defender on the Commodore 64," he reminisces, "when I decided at the age of 12 or so that I want to be a computer programmer when I grow up."

Jon was previously employed as a senior .NET developer at a very well-known Internet services company whom you're more likely than not to have directly done business with. However, this blog and all of jondavis.net have no affiliation with, and are not representative of, his former employer in any way.

Contact Me 

Tag cloud


<<  May 2021  >>

View posts in large calendar