I’m pretty new with C# and .NET. I’m trying to model a graph with heterogeneous data. I mean i would like to be able to do something like this:
// Simple graph modeling using generics
public class Node<T>
{
private T data;
public Node(T data)
{
this.data = data;
}
}
public class Edge<T, U>
{
private T source;
private U destination;
public Edge(T source, U destination)
{
this.source = source;
this.destination = destination;
}
}
Building it this way:
Node<Person> p = new Node<Person>(new Person("Red John"));
Node<Computer> c = new Node<Computer>(new Computer("MyComputer"));
graph.AddNode(p);
graph.AddNode(c);
graph.AddEdge(new Edge<Person, Computer>(p, c));
But of course the graph class definition won’t let me do this:
public class Graph<T> where T : CommonBaseClass
I’ve also tried defining a base class for both person and computer, but of course it’s not working. Any help/idea suggestion? I need heterogeneous data because i have to merge list of different nodes.
Thanks for helping!
In cases like this, it can be convenient to have your generic classes derive from non-generic classes. That way, you can refer to all types of Nodes through a simple
Nodeclass:If type
objectis too primitive, you can use generic constraints instead:Now, your
Graphclass can allow any type ofNodeandEdge: