Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add events using Extension methods

I have found several posts about Raising events with an extension method, however my question is a bit different:

I have an interface like this:

public interface IStateMachine 
{
    void SetState(IState NewState);
    IState GetState();
}

Using this interface I can create an extension method like follows:

public static void ChangeState(this IStateMachine StateMachine, IState NewState) 
{
    StateMachine.GetState().Exit();
    StateMachine.SetState(NewState);
    StateMachine.GetState().Enter();
}

What I really want is that there will be events that need to be fired, e.g.: a statechange-event.

However I don't want the StatechangeEvent to be a part of the IStateMachine interface, but it seems that that's the only way. I have several classes that implement IStateMachine, and therefore I have to redo the same code every time.

like image 350
avanwieringen Avatar asked Mar 04 '13 13:03

avanwieringen


1 Answers

In C#, there are only extension methods. No extension properties or events.

You will have to declare the event on the interface.
To avoid the need to write the same event code over and over, you can create a base class.

Another possibility would be to "manually" implement the Publish-Subscribe pattern. That's what events in C# are.

You can add the extension methods Subscribe and Unsubscribe to IStateMachine.

They would use a possibly static class StateMachineSubscribers which also exposes the Subscribe and Unsubscribe methods. Additionally, it exposes a Raise method used by your ChangeState extension method.

like image 64
Daniel Hilgarth Avatar answered Oct 07 '22 08:10

Daniel Hilgarth