tags:

views:

56

answers:

2

Hi everyone.

I have the following code:

public void ParseNetworkPacket(IAsyncResult iResult)
    {
        NetworkConnection networkConnection = (NetworkConnection)iResult.AsyncState;

        string teste = NetworkPacketType.ToString();

        switch (this.NetworkPacketType)
        {
            case NetworkPacketType.ShotPacket:
                break;
            case NetworkPacketType.ShotResponsePacket:
                break;
            case NetworkPacketType.ChatMessagePacket:
                break;
            default:
                break;
        }

        networkConnection.BeginReadPacket();
    }

NetworkPacketType is a enum defined by me. In the switch, depending on the type of the enum, I would call a different method. I would like to do that not using switch, because I may have too many enum types. Is there any other way to do that? Or wih an enum that's the only possible way?

Thanks in advance.

+1  A: 

Is this what you want? http://stackoverflow.com/questions/2460478/operator-for-enums
Try the first answer.

Veer
Jon Skeet's answers won't fail you. :)
JYelton
+1  A: 

Beside using a map as suggested in the answer linked by Veer, you could also use reflection. If you would name your methods like the enum values for example, it could be done like this:

public void ParseNetworkPacket(IAsyncResult iResult)
    {
        NetworkConnection networkConnection = (NetworkConnection)iResult.AsyncState;

        string teste = NetworkPacketType.ToString();

        string methodName = this.NetworkPacketType.ToString();

        MethodInfo methodInfo = GetType().GetMethod(methodName, 
            BindingFlags.Instance | BindingFlags.NonPublic);

        methodInfo.Invoke(this, /* your arguments here */);

        networkConnection.BeginReadPacket();
    }

private void ShotPacket() 
{
    ....
}

But I would not really recommend this approach if not absolutely neccessary. It can be a pain to maintain this, among other things.

Patko