How could I make this code more generic in the sense that the Dictionary key could be a different type, depending on what the user of the library wanted to implement? For example someone might what to use the extension methods/interfaces in a case where there “unique key” so to speak for Node is actually an “int” not a “string” for example.
public interface ITopology
{
Dictionary<string, INode> Nodes { get; set; }
}
public static class TopologyExtns
{
public static void AddNode(this ITopology topIf, INode node)
{
topIf.Nodes.Add(node.Name, node);
}
public static INode FindNode(this ITopology topIf, string searchStr)
{
return topIf.Nodes[searchStr];
}
}
public class TopologyImp : ITopology
{
public Dictionary<string, INode> Nodes { get; set; }
public TopologyImp()
{
Nodes = new Dictionary<string, INode>();
}
}
Make the interface generic, then use a
Func<INode,T>as a selector for the key. This assumes that you want the key for the dictionary to be extracted from the node. If this isn’t a hard requirement, then you could specify the key itself using the generic type specifier in the signature.You might also consider making INode a generic type. That would allow you to specify the Key as a property of the generic type which the implementation could defer to the appropriate “real” key. This would save you from having to supply either the key or a selector for the extension method.
Alternative:
Used as: