I have next code that represents graph edges and nodes (simplified for question):
public class Node
{
}
public class Edge
{
public Node Source { get; set; }
public Node Target { get; set; }
}
Now I want to extend this classes for describing mine topology:
public class MineNode : Node
{
public double FanPressure { get; set; }
}
public class MineTunnel : Edge
{
public double Length { get; set; }
public double CrossSectionArea { get; set; }
public MineTunnel()
{
Source = new MineNode();
Target = new MineNode();
}
}
The problem is that I want to access additional data provided by MineNode when using Source and Target properties, but I can access only Node fields because they are declared in base class:
MineTunnel t = new MineTunnel();
Console.WriteLine(t.Source.FanPressure); //Error
The only way to access FanPressure is to cast Source to MineNode but code become ugly this way.
Console.WriteLine(((MineNode)t.Source).FanPressure); //OK
The another way is maybe to use somehow generics in base class declaration. But I’m not sure is that a good practice in my situation.
So, how can I solve such problem – extend functionality of base class fields?
Thanks.
I think generics is the way to go here…
Try this:
Then you can extend the Node and Edge classes with:
Please correct me if this is wrong or doesn’t work… 🙂