I have two classes ClassA and CLassB. ClassA is an abstract class. ClassB derives from ClassA. I have one DTO named ParentDTO.
public class ParentDTO
{
public int UserId { get; set; }
}
public abstract class ClassA
{
public abstract void CreateUser(ParentDTO dto);
}
public class ClassB : ClassA
{
public override void CreateUser(ParentDTO dto)
{
Console.WriteLine("You are in class ClassB");
}
}
Now I have one DTO(MyDTO), which derives from ParentDTO.
public class MyDTO: ParentDTO
{
public int MyID { get; set; }
}
I have extended ClassB further:
public class ClassC : ClassB
{
public override void CreateUser(ParentDTO dto)
{
var mydto = (MyDTO) dto;// This throws cast exception
mydto.MyID=222;
}
}
I am using the above code as :
ClassC c = new ClassC();
ParentDTO dto=new ParentDTO();
c.CreateUser(dto);
Can someone please tell me how to cast DTO above in CreateUser method of ClassC. I want to use mydto.MyID in my code. I know I am doing something like casting Animal to Lion instead of Lion to Animal. But is there any way to use child DTO ID? Can someone please tell me what am I doing wrong?
The other answers are correct, but the reason for this behavior would be clearer with a better understanding of the difference between “static type” and “run-time type”, which they do not discuss. Static type is the type of a variable in your C# code, while run-time type is the type of an actual object in memory.
We all know that static type and run-time type may differ. Consider:
The variable
arefers to an instance of typeB. The static type of the variable isA, but the run-time type of the object isB.We can also think of
aas holding a reference of type A that refers to an instance of type B. This is allowed if and only if type B is derived from (or equal to) type A.The following, therefore, is not allowed:
Here, you are attempting to assign a reference to an instance of type A (run-time type) to a variable of (static) type B. A is not derived from or equal to B, so the assignment is not allowed. Similarly, the following assignments are not allowed:
The cast operator complicates things somewhat, but the underlying issue is the same: you are attempting to set a reference to point to an object whose run-time type is not derived from or equal to the static type of the reference:
Again, this might make more sense if we substitute
objectforAandstringforB:Similarly, with your types: