Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two extension methods with same name

I have the following two extension methods (the body of the methods is not particularly important for my question, but including the code anyway)

public static class DictionaryExtensions
{
    public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, TValue defaultValue)
    {
        return (source.ContainsKey(key) ? source[key] : defaultValue);
    }
}

public static class WebExtensions
{
    public static T GetValue<T>(this HttpContext context, string name, T defaultValue)
    {
        object value = context.Request.Form[name] ?? context.Request.QueryString[name];
        if (value == null) return defaultValue;
        return (T)value;
    }
}

These two methods share the same name but they extend two very different types. I would expect the following code to be simple and the compiler to be able to pick the appropriate extension method:

var myDict = new Dictionary<int, string>()
{
    { 1, "foo" },
    { 2, "bar" }
};
var result = myDict.GetValue(5, "baz");

However, for some unknown reason, Visual Studio refuses to compile my code with the following compile-time error: "The type 'System.Web.HttpContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web'" . This error tells me that the compiler selected the GetValue extension method in the WebExtensions class instead of the one in the DictionaryExtension class.

I was able to get around the problem with the following:

var result = DictionaryExtensions.GetValue(myDict, 5, "baz");

but I'm trying to understand why the compiler was confused in the first place. Does anybody know why?

like image 969
desautelsj Avatar asked Dec 31 '14 18:12

desautelsj


1 Answers

Another option is to break your 2 Extension classes out into separate namespaces and do not add a using statement where the WebExtensions class resides in your consuming code. That way the compiler won't try and resolve GetValue to WebExtensions.

like image 54
Steve Danner Avatar answered Oct 08 '22 16:10

Steve Danner