Upcasting without any added data fields.

Posted by Benjamin Manns on Stack Overflow See other posts from Stack Overflow or by Benjamin Manns
Published on 2010-03-15T22:29:22Z Indexed on 2010/03/15 22:39 UTC
Read the original article Hit count: 226

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about casting