1 year ago

#359091

test-img

Willy

Return EventHandler as out parameter depending on condition

I have some custom events defined in my class that I am subscribing and unsubscribing in my code to them:

public event EventHandler<CustomEventArgs1> CustomEvt1Received;
public event EventHandler<CustomEventArgs2> CustomEvt2Received;
public event EventHandler<CustomEventArgs3> CustomEvt3Received;
public event EventHandler<CustomEventArgs4> CustomEvt4Received;

And all these custom event args inherit from a base class:

public Class CustomBaseEventArgs
{
}

public Class CustomEventArgs1 : CustomBaseEventArgs
{
}
public Class CustomEventArgs2 : CustomBaseEventArgs
{
}
public Class CustomEventArgs3 : CustomBaseEventArgs
{
}
public Class CustomEventArgs4 : CustomBaseEventArgs
{
}

Now I have a method that depending on a condition I would like to return the appropriate event handler as an out parameter, something like this:

private string GetEventHandler(out EventHandler evt)
{
    evt = null;
    if (condition1) return CustomEvt1Received;
    else if (condition2) return CustomEvt2Received;
    else if (condition3) return CustomEvt3Received;
    else if (condition4) return CustomEvt4Received;
    else return evt;
}

then from my code I would like to do:

string err = GetEventHandler(out EventHandler myEvent);
myEvent?.invoke(this, ...);

How can I do this?

c#

visual-studio-2019

.net-4.5

0 Answers

Your Answer

Accepted video resources