views:

37

answers:

2

Hi,

Using extension methods for C#, how can include an AddNode method (see below) in the ExtensionMethods class for reuse, as opposed to having to put it in the implementation class itself (where I couldn't reuse it). The AddNode extension method needs to be able to access the List parameter in the implementation.

I've tried the below however I'm finding within the AddNode extension method it can't "see" the Nodes list, even though this list is specified in the ITopology interface, and the extension method is being applied to this ITopology interface.

Some of the .net generics collections classes seem to be able to bundle their "add" methods, so am I taking the wrong approach here somewhere?

    public interface ITopology
    {
        List<INode> Nodes { get; set; }
    }

    public interface INode 
    {
        List<INode> GetChildren(NodeDepthType nodeDepth);
    }

    public static class ExtensionMethods
    {

        public static bool AddNode(this ITopology topIf, INode node)
        {
            this.Nodes; // <== ** Can't resolve symbol Nodes **
            return true;
        }

    }

namespace TopologyLibrary_Client
{
    using Topology;

    public class TopologyImp : ITopology
    {
        public List<INode> Nodes { get; set; }
    }
}
+2  A: 

You access topIf, not this:

    public static bool AddNode(this ITopology topIf, INode node)
    {
        topIf.Nodes;
        return true;
    }
Dean Harding
+1  A: 

Replace the code in AddNode with the following:

public static bool AddNode(this ITopology topIf, INode node) 
{ 
    topIf.Nodes; // <== Note the use of topIf here.
    return true; 
} 

You forgot to use the reference topIf to actually access the Nodes property.

John Källén