0

I am doing the exact same thing as mentioned here:Which mechanism is a better way to extend Dictionary to deal with missing keys and why?

Making a getter to a dictionary that returns a default. It compiles just fine but anyone trying to use it gets a compiler error saying … and no extension method 'ObjectForKey' accepting a first argument of type System.collections.Genericc.Dictionary could be found.

Here is the definition

public static TValue ObjectForKey<TKey,TValue>(this Dictionary<TKey,TValue> dictionary, TKey key)
{
    TValue val = default(TValue);
    dictionary.TryGetValue(key,out val);
    return val;
}

Here is how I try to use it

Dictionary<string,object> dictionary = <stuff>
object val = dictionary.ObjectForKey("some string");

Any thoughts?

Community
  • 1
  • 1
user2292539
  • 245
  • 1
  • 11
  • 1
    I'm not getting this error here. Please provide more context, or try reducing the use case to its minimum, maybe as a new project. – Luc Morin Feb 11 '14 at 04:21

1 Answers1

2

You should define your extension method inside of a static (to make is extension) and public (to make it accessible outside of the class) class

public static class MyExtensions
{
    public static TValue ObjectForKey<TKey,TValue>(this Dictionary<TKey,TValue> dictionary, TKey key)
    {
        TValue val = default(TValue);
        dictionary.TryGetValue(key,out val);
        return val;
    }
}   
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • ...and make sure the namespace is included in your `using` statements if it isn't the same as the class where the extension is being used. – Erik Noren Feb 11 '14 at 04:19
  • 1
    @Selman22 It would not compile if that was not already the case. – Luc Morin Feb 11 '14 at 04:20
  • They might have defined the extension inside another instance class. It would compile but it wouldn't be detected as a proper extension method when it came to invoke it, if I remember correctly. – Erik Noren Feb 11 '14 at 04:22
  • Ok it was there, but not static. Thanks! Problem solved. Ill mark soon as its able. – user2292539 Feb 11 '14 at 04:22
  • Actually, when I try to define an extension method inside an instance class, I get a compile error "Extension method must be defined in a non-generic static class" – Luc Morin Feb 11 '14 at 04:27