Do you think you are deleting a type?
I assume that you thought that including a virtual method in the Message type would break the layer abstraction (for example, you might need a clean separation of message processing from the message itself). Perhaps consider a template. This will allow you to separate the Message class from the Message processing itself.
If you have any of this structure.
abstract class CommsMessage {} class Message1 : CommsMessage {} class Message2 : CommsMessage {}
You can reorganize
abstract class CommsMessage { public abstract void Visit(CommsMessageVisitor v); } class Message1 : CommsMessage { public void Visit(CommsMessageVisitor v) { v.Accept(this); } } class Message2 : CommsMessage { public void Visit(CommsMessageVisitor v) { v.Accept(this); } } interface CommsMessageVisitor { void Accept(Message1 msg1); void Accept(Message1 msg2); }
At this point, you excluded tip-throws. Now you can rewrite your code as
void ProcessIncomingMessage(CommsMessage msg) { new MyVisitor().Visit(msg); } class MyVisitor : CommsMessageVisitor { void Accept(Message1 msg1) { ProcessMessageType1(msg1); } void Accept(Message1 msg2) { ProcessMessageType2(msg2); } }
Of course, there may be reasons why you cannot do this, but it is always better to avoid typecasting if you can!
source share