0

I have a ReadOnlyCollection of a custom Interface type (IMyInterface). I want to add an extension method to the custom Interface type. However, my extension method is not showing up when I access an item inside the ReadOnlyCollection. Here's my code :

public static class MyClass
{
    public static string GetValueByName(this IMyInterface myInterface, string myName)
    {
        foreach (var name in myInterface.names) //
        {
            if (myName == name)
                return name;
        }
        throw new ArgumentException(myName + " not found.");
    }
}

When I try to access it by doing something like,

MyMethod[0].<extension method>   //MyMethod returns a ReadOnlyCollection<IMyInterface>

The extension method is not showing up in the pop-up available after the MyMethod[0] (in Visual Studio) meaning its not available. What could I possibly be missing? Is it possible to add an extension method for the item in the ReadOnlyCollection?

Setafire
  • 719
  • 2
  • 9
  • 21
  • 3
    Sounds like you haven't included the `using` for the the extension's namespace. – Neil Smith Sep 19 '14 at 19:40
  • Wow! I thought Visual Studio will detect that automatically and prompt me to add it. Didn't realize it was missing the namespace! Thanks @NeilSmith . That worked! – Setafire Sep 19 '14 at 19:44
  • 1
    I wonder why people use extension method for their own class/interface! – Yogee Sep 19 '14 at 19:44
  • @Yogee How else would you provide the concrete implementation of a method for an interface? – Servy Sep 19 '14 at 19:45
  • @Servy That's a good point i never used extension method's in such a way. – eran otzap Sep 19 '14 at 19:51
  • 1
    @eranotzap That's what you're doing any time you create an extension method on an interface. Creating an extension method for a class you have control over the source of is something that can also make sense, but it's a much narrower/unusual situation than for interfaces. – Servy Sep 19 '14 at 19:53

1 Answers1

1

Guess I'll turn it into an answer:

You haven't included the using statement for your extension's namespace.

For example, if you wrote the extension in MyNamespace, you would have to include using MyNamespace in the class where you're using the extension.

Neil Smith
  • 2,565
  • 1
  • 15
  • 18