I have several classes derived from a base class
public interface IBase {}
public class Base : IBase {}
public class ClassA : Base, IBase {}
public class ClassB : Base, IBase {}
public class ClassC : Base, IBase {}
Now I want to send instances of each of these classes via an event handler to a common location, so I thought "Great .. I'll just subclass Base
from EventArgs
and pass each of my instances into a common method that can send it off" (note that the following is not real code)
public interface IBase : IEventArgs
public class Base : EventArgs, IBase {}
public class ClassA : Base, IBase {}
public class ClassB : Base, IBase {}
public class ClassC : Base, IBase {}
EventHandler Update;
void SendClass(IEventArgs data)
{
Update?.Invoke(this,data);
}
..
SendClass(new ClassA());
SendClass(new ClassB());
SendClass(new ClassC());
Except that IEventArgs
is apparently a figment of my imagination. So this can't be done.
It look like the only valid solution is to define a customs Send
method for each class that I want to send. EG:
void SendClassA(ClassA data)
{
Update?.Invoke(this,data);
}
void SendClassB(ClassB data)
{
Update?.Invoke(this,data);
}
void SendClassC(ClassC data)
{
Update?.Invoke(this,data);
}
While this works, it gives me a bad code smell feeling as I am basically repeating a very simple method many times.
Is there another design that achieves what I want from an imaginary IEventArgs
?
I could achieve what I want with a bunch of Up and Down casting, but again that also gives me a bad feeling (see Casting vs using the 'as' keyword in the CLR)