0

Since trying to use them will cause an error what is the workaround to get the same effect as them?

My Base Class:

public abstract class IPacket
{
    public abstract int Identifier { get; set; }

    public abstract void Handle();
}

Child Class:

public class DoSomething : IPacket
{
    public override int Identifier
    {
        get
        {
            return 1;
        }
    }

    public override void Handle()
    {
        // Do Something
    }
}

Incoming Packet Routing:

Dictionary<Byte, IPacket> Packets = new Dictionary<byte, IPacket>
    {
        {DoSomething.Identifier, DoSomething} // <-- Not Possible
    };

Packets[ID].Handle();

Basically I get a packet from Server which contains an Identifier. I use this identifier to find the handler for that packet from a dictionary and pass the packet to it's handler.

  • Why don't you allocate one DoSomething before you try to put it in the dictionary? – Frank Hileman Jul 1 '14 at 16:34
  • 1
    Shouldn't it be Packets.add(xxx.Identifier,xxx); given xxx is of type Ipacket ? – Tulains Córdova Jul 1 '14 at 16:36
  • @user61852 Well that is what is being done. – LRNAB Jul 1 '14 at 17:10
  • 1
    @LRNAB I don't see that code in your question. On the other hand I don't know C#, just Java, and perhaps the operation is implied. – Tulains Córdova Jul 1 '14 at 17:24
  • 1
    @LRNAB DoSomething is a class. You need to instantiate a new DoSomething in order to add it to the dictionary. In order to access that DoSomething's Identifier, you must instantiate the DoSomething before adding it to the dictionary. – Andrew Hoffman Jul 1 '14 at 17:50
1

Since you dispatch Handle on an identifier and not on packet object's class, I don't see any benefit in having Handle as a method of packet objects.

Think about some PacketProcessor that handles packets of certain type, and a Dictionary<Identifier, PacketProcessor>.

0
DoSomething newSomething = new DoSomething();
Dictionary<int, IPacket> Packets = new Dictionary<int, IPacket>
{
    { newSomething.Identifier, newSomething } // <-- Possible
};

IPacket as an abstract class and not an interface isn't intuitive naming.

// Alternatively,
public interface IPacket
{
    int Identifier { get; }
    void Handle();
}

public class DoSomething : IPacket
{
    public int Identifier { get; set; }
    public void Handle() { }
}

...

int id = 1;
Dictionary<int, IPacket> Packets = new Dictionary<int, IPacket>
{
    { id, new DoSomething { Identifier = id } }
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.