I’m not sure if that is possible in C# but I would like to have events in an abstract class with a strong typed ‘sender’ argument.
There is my code
abstract class Base
{
public degate void MyDelegate(Base sender, object arg);
public event MyDelegate SomeEvent;
protected void RaiseSomeEvent(object arg)
{
if (SomeEvent != null)
SomeEvent(this, arg)
}
}
class Derived : Base
{
// ?
}
var obj = new Derived();
obj += EventHandler;
public void EventHandler(Derived sender, object arg)
{
}
So is that possible by manipuling generic where clause for example ?
You could definitely make it generic – but you wouldn’t really want to in the case that you’ve given.
Base.SomeEventdoesn’t “know” (at compile-time) what type it is – so you can’t make it depend on some type parameter which will be “the right type”. You could do something horrible like:(You may need
(T) (object) thisto keep the compiler happy.)And then:
but it gets very ugly, and there’s nothing to stop this from happening:
At that point, the cast will fail when the event is raised.
I would suggest that if you really want to be sure that the sender is the right type, you ignore the
senderparameter and capture the variable you’re using to subscribe in the first place: