I've been trying to write a simple Static-class State Machine for my application to notify other controls and code when the system state changes. And I think I almost have it, but I'm running into a small issue that I'm not sure how to work around.
Here's the code:
// An enum denoting the 3 States
public enum Status { Error = -1, Working, Ready }
// The main state change class
public static class Sys
{
// system status
private static Status state;
// delegate and event
public static delegate void StateChangeHandler(object sys, SysInfoEventArgs sysStateInfo);
public static event StateChangeHandler OnStateChange;
public static Status State
{
get { return state; }
set
{
SysInfoEventArgs sysInfo = new SysInfoEventArgs(state, value);
state = value;
OnStateChange(this, sysInfo);
}
}
}
/// <summary>Contains previous and current state info</summary>
public class SysInfoEventArgs : EventArgs
{
public readonly Status oldState;
public readonly Status newState;
public SysInfoEventArgs(Status oldState, Status newState)
{
this.oldState = oldState;
this.newState = newState;
}
}
The problem I am having is with this line:
OnStateChange(this, sysInfo);
Specifically, the word "this" is illegal. And I understand why: "this" is supposed to refer back to the self of an instantiated object (not a static class).
I would prefer to have a Static class for my state machine rather than one that I can instantiate multiple copies of. (Not that it would be such a bad thing, but I feel it makes the code cleaner having a static class.)
So how am I supposed to work this?
Update:
As a follow-up, I selected Jon Skeet's answer as the correct one because the issue was more about the approach I was taking, rather than a technical failure that I was having. Although, pretty much all of the other answers below fix the technical glitch I was dealing with.
Oddly enough, as I was reviewing with my co-worker the application that I wrote, she pointed out that the program should probably track both the state of the server connection as well as the state of the work being done. (Yes, Virginia, this means I need 2 state machines... Ergo, remove all the "static" keywords from the code above and make it a regular class was the smart approach.)
Thanks again, everyone!