Reputation: 26227
I can't seem to get the following extension method to be found in another class in the same namespace (MyProject.Util
).
using System.Collections.Specialized;
namespace MyProject.Util
{
public static class Extensions
{
public static string Get(
this NameValueCollection me,
string key,
string def
)
{
return me[key] ?? def;
}
}
}
As you can see it's basically another version of foo[bar] ?? baz
, but I still don't understand why VS2008 fails to compile telling me that no version of Get
takes two arguments.
Any ideas?
Upvotes: 2
Views: 2067
Reputation: 32575
I had a similar issue recently and traced it down to not referencing System.Core (the project was compiled against 3.5, but that reference had accidentally been removed while experimenting with VS2010/.Net 4.0).
Upvotes: 0
Reputation: 941465
Works fine when I try it. There's really only one failure mode: forgetting to add a using statement for the namespace that contains the extension method:
using System.Collections.Specialized;
using MyProject.Util; // <== Don't forget this!
...
var coll = new NameValueCollection();
coll.Add("blah", "something");
string value = coll.Get("blah", "default");
Upvotes: 1
Reputation: 532465
Is the class in the same assembly as the class where it is being used? If no, have you added a reference to that assembly?
Upvotes: 2
Reputation: 4108
The following seems to work for me ...
using System.Collections.Specialized;
namespace MyProject.Util
{
class Program
{
static void Main(string[] args)
{
var nvc = new NameValueCollection();
nvc.Get( )
}
}
}
namespace MyProject.Util
{
public static class Extensions
{
public static string Get(
this NameValueCollection me,
string key,
string def
)
{
return me[key] ?? def;
}
}
}
Have you checked your target framework?
Upvotes: 1
Reputation: 53944
You can't use the extension method like a static method as in NameValueCollection.Get
. Try:
var nameValueCollection = new NameValueCollection();
nameValueCollection.Get( ...
Upvotes: 3
Reputation: 34198
Are you importing your namespace (with using MyProject.Util
) in the file where you're using the method? The error message might not be obvious because your extension method has the same name as an existing method.
Upvotes: 6