0

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)

Peter M
  • 7,309
  • 3
  • 50
  • 91
  • What problem do you face if you use interface instead of classes? – Chetan Aug 24 '17 at 14:02
  • @ChetanRanpariya It doesn't work. `Invoke` can't determine that the parameter was derived from `EventArgs` if you pass it as an interface. – Peter M Aug 24 '17 at 14:04

2 Answers2

0

Is this what you're looking for?

public class BaseEventArgs : EventArgs {
    public IBase Data;
}

public event EventHandler<BaseEventArgs> Update;

void SendData(IBase data)
{
    Update?.Invoke(this, new BaseEventArgs { Data = data } );
}
0

You might want something like this:

void Main()
{
    SendClass(new ClassA());
    SendClass(new ClassB());
    SendClass(new ClassC());
}

public class Base { }

public class ClassA : Base { }
public class ClassB : Base { }
public class ClassC : Base { }

public delegate void SendClassHandler(Base data);

public event SendClassHandler Update;

public void SendClass(Base data)
{
    Update?.Invoke(data);
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172