user2292539
user2292539

Reputation: 245

Dictionary extension compiles but not callable

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?

Upvotes: 0

Views: 92

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

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;
    }
}   

Upvotes: 2

Related Questions