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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With