Ok i have a question that is the same as above:
What if you want to literally combine two events, like
public interface IInterfaceWithEvents
{
event EventHandler EventFired;
}
public class ClassA : IInterfaceWithEvents
{
public event EventHandler EventFired;
public void Invoke()
{
if(EventFired != null)
EventFired(this, EventArgs.Empty);
}
}
public class ClassB : IInterfaceWithEvents
{
public event EventHandler EventFired;
public void Invoke()
{
if(EventFired != null)
EventFired(this, EventArgs.Empty);
}
}
What I need is to create 'ClassA' and convert it the interface, then from there convert it into a 'ClassB' object. But sadly, C# does not allow this type of casting. Instead I trying to figure out if there is a way to combine the events of the 'ClassA' object with the events of the 'ClassB' object:
ClassA ca;
// the create method returns an IIterfaceWithEvents object created from
// an external library (so the calling code does not know the literal type that
// is ClassB)
IInterfaceWithEvents i = external.create( some_args );
// since this is illegal
ca = (ClassA)i; //<- exception for wrong cast
// i need to just physically convert the 'i' reference into the 'ClassA' object:
public static ClassA From(IInterfaceWithEvents ievents)
{
ClassA ca = new ClassA();
// is there some way to do this:
ca.EventFired = ievent.EventFired;
}
// if so I could now just do this to convert 'ca' to 'i'
ca = ClassA.From(i);
// but downside is, if the ClassB (i) reference calls on EventFired then
// the 'ClassA (ca) EventFired event will never be called, and vice-versa
I could get them combined through a delegate, but it really defeats the purpose. And I have to use events and the Interface, if I could use an abstract class I would be all ok
here, but sadly I cannot. So my question one more time (just in case the above examples were too crude):
Does C# have a way to pass the reference from one event to another, or literally combine the two events (basically making them the same event).
Or:
Is there a way to just cast 'ClassA' to 'IInterfaceWithEvents' then from 'IInterfaceWithEvents' to ClassB. <- this would be awesome, but I do understand why the CLR does not allow it.