2

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?

Deniz Dogan
  • 25,711
  • 35
  • 110
  • 162

6 Answers6

6

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.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
3

You can't use the extension method like a static method as in NameValueCollection.Get. Try:

var nameValueCollection = new NameValueCollection();
nameValueCollection.Get( ...
tanascius
  • 53,078
  • 22
  • 114
  • 136
2

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?

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1

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?

WestDiscGolf
  • 4,098
  • 2
  • 32
  • 47
  • Target framework version sounds like the most likely culprit to me. @blahblah: Make sure you're targetting .NET 3.5 or later. – Damian Powell Apr 20 '10 at 12:31
  • I've always been using .NET 3.5. I'm doing this in ASP.NET MVC by the way, I'm not even sure I can do that with anything below 3.5. – Deniz Dogan Apr 20 '10 at 12:32
1

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");
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

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).

Chris Shaffer
  • 32,199
  • 5
  • 49
  • 61