Reputation: 287
I'm new to C# generics so please bear with me. I wanna cast an object of type (say)NodeRef to NodeRef<TNode>. Is it possible? If, yes How ? Currently this is what I have
public class Program
{
static void Main(string[] args)
{
var nodeRef = new NodeRef();
var newNodeRef = (NodeRef<MyNode>) nodeRef;
//above line throws up at Runtime.
}
}
public class NodeRef
{
private int id;
}
public class NodeRef<TNode> : NodeRef
{
private TNode tNode;
public void Print()
{
Console.WriteLine(tNode.ToString());
}
}
I'm currently getting this exception: System.InvalidCastException.
Edit:
Why won't it throw a compile time error, though ? MyNode is just a dummy class
public class MyNode
{
public int Id { get; set; }
public string Name { get; set; }
}
Upvotes: 0
Views: 117
Reputation: 59101
This problem is not because you are using generics. The problem is that NodeRef<T>
is a NodeRef
. But not all NodeRef
are necessarily NodeRef<T>
. It depends on what you wrote when you first called new
.
This would also happen if you wrote your derived object to look like this:
public class SomeDerivedClass : NodeRef
{
// ...
}
static void Main(string[] args)
{
var nodeRef = new NodeRef();
var newNodeRef = (SomeDerivedClass) nodeRef;
}
For a cast to work you have to cast to the same type as your actual instance (the type you specified when you called new
), or one of its base classes. For example, this code will not throw an exception:
public class Program
{
static void Main(string[] args)
{
NodeRef nodeRef = new NodeRef<MyNode>();
var newNodeRef = (NodeRef<MyNode>) nodeRef;
}
}
Casts like this don't convert the type of the object instance to another type (unless you write a custom conversion operator, which you didn't do here). These types of cast simply let you tell the compiler "I know the object is actually this other type. Let me work with it that way". If you make a mistake, the .Net framework will throw an exception when you are running the program.
Upvotes: 4