Upcasting without any added data fields.
- by Benjamin Manns
In my project I have a generic Packet class. I would like to be able to upcast to other classes (like LoginPacket or MovePacket).
The base class contains a command and arguments (greatly simplified):
public class Packet
{
public String Command;
public String[] Arguments;
}
I would like to have be able to convert from Packet to LoginPacket (or any other) based on a check if Packet.Command == "LOGIN". The login packet would not contain any new data members, but only methods for accessing specific arguments. For example:
public class LoginPacket : Packet
{
public String Username
{
get { return Arguments[0]; }
set { Arguments[0] == value; }
}
public String Password
{
get { return Arguments[1]; }
set { Arguments[1] == value; }
}
}
It would be great if I could run a simple code that would cast from Packet to LoginPacket with something like LoginPacket _Login = (LoginPacket)_Packet;, but that throws a System.InvalidCastException.
It seems like this would be an easy task, as no new data is included, but I can't figure out any other way than copying everything from the Packet class to a new LoginPacket class.