C # extension method doesn't seem to exist

I cannot find the following extension method that can 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, this is basically a different version foo[bar] ?? baz

, but I still don't understand why VS2008 fails to compile, telling me that neither version Get

takes two arguments.

Any ideas?

+2


a source to share


6 answers


Are you importing your namespace (c using MyProject.Util

) into the file where you use this method? The error message may not be obvious because your extension method has the same name as the existing method.



+3


a source


You cannot use an extension method as a static method as in NameValueCollection.Get

. Try:



var nameValueCollection = new NameValueCollection();
nameValueCollection.Get( ...

      

+3


a source


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 the target structure?

+1


a source


Is the class in the same assembly as the class in which it is used? If not, have you added a link to this assembly?

+1


a source


Works well when I try. There really is only one failure mode: forget 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");

      

+1


a source


I recently had a similar problem and traced it down without referencing System.Core (the project was compiled against 3.5, but this link was accidentally deleted while experimenting with VS2010 / .Net 4.0).

0


a source







All Articles