Search code examples
c#static-class

Static class stored as a property


I have a static abstract class called State, it defines the abstract methods start() and update(), and then I have multiple classes which implement State.

Now I want to create a class, let's call it StateMachine, that has a property called currentState. I want to be able to set this property pointing to a static class implementing state so I can run things like currentState.update().

Now comes my question:

What should be the type of the property? I'd say State but I feel like there's something more to it. Also, how would I go into setting the property? is

currentState = ClassThatImplementsState;

a valid thing to do?

EDIT: Ok, so I just learned that you cannot inherit from a static class in C#. I'd like to know a way of doing something similar to this that would allow me both the polymorfism and not having to instantiate the state objects. Is there such a thing?


Solution

  • If State is a static class, you can't have multiple classes that "implement", i.e. derive from it. When, on the other hand, it is an abstract class, you can derive from it. But it can't be both.

    EDIT: I think what you actually want is a Singleton rather than an abstract or static class. See http://msdn.microsoft.com/en-us/library/ff650316.aspx for hints how to implenent the Singleton pattern in C#.

    EDIT 2: If your application is multithreaded, be sure to use a thread safe variant of the Singleton pattern.