Search code examples
c#extension-methodsreadonly-collection

Extension Method to an item of a ReadOnlyCollection


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?


Solution

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