Jeffrey

Jeffrey

  • NA
  • 1
  • 0

Extension Methods on a Generic Class

Jun 12 2008 7:57 PM

I appologize if this topic is already addressed somewhere. The Search bar was throwing errors, so I couldn't check.

Anyway, I'm looking to write an extension method for a generic class (specifically Dictionary). Currently, the only way I can get this to work is with the following code.

using System.Collections.Generic;

namespace CustomExtensions

{

      public static class DictExtend

      {

            public static TValue Try<TKey, TValue>(this Dictionary<TKey, TValue> Dict, TKey key, TValue defaultvalue)

            {

                  return defaultvalue;

            }

      }

}

Eventually this method will do things, but that's unimportant right now. You'll notice that I had to make the method itself generic in order to deal with the Dictionary Class being generic. When I didn't, Visual Studio told me that it couldn't identify the TKey and TValue types. I just don't see specifying my dictionary types when I call the method ending anywhere close to well. Is there any way to define my generic types based on the Dictionary instance I'm operating on instead?

Thanks!