Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6727393
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T10:02:39+00:00 2026-05-26T10:02:39+00:00

I am new to the state pattern implementation in C#, could you provide some

  • 0

I am new to the state pattern implementation in C#, could you provide some info on how you implement it.

I am refactoring a state machine in C# using the state pattern. Currently my state machine contains 5 states and it is only possible to go forward or backward througout the states,i.e. from state 1 you need to go to state 2, 3 and 4 to finally arrive to state 5. enter image description here

I am able to go forward just doing

       mainclass.State = new NextSate();

which creates a new state every time you want to go forward, however, once all of them have been created and/or you want to go backward I would need to go to the same states, not just a new one. How can I do that? Is there any better way to do it simple?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T10:02:40+00:00Added an answer on May 26, 2026 at 10:02 am

    Strictly speaking, if you’re implementing the classic GoF State pattern then the State subclasses themselves are responsible for knowing about and performing the State transitions. The holder of the State isn’t responsible for managing the transitions and a large part of the intent of the pattern is to encapsulate the state transition behaviour in the State objects and thus for the client to delegate to them. I’ve introduced a Factory that ensures that there is only ever a single instance of each State subclass to ensure that the same instance is reused when moving back and forth through the states.

    public abstract class State
    {
       protected StateFactory _factory;
       protected IStateUser _context;
    
       public State(StateFactory factory, IStateUser context)
       {
          _factory = factory;
          _context = context;
       }
    
       protected void TransitionTo<T>(Func<T> creator) where T : State
       {
           State state = _factory.GetOrCreate<T>(creator);
           _context.CurrentState = state;
       }
    
       public abstract void MoveNext();
       public abstract void MovePrevious();
    }
    
    public class State1 : State
    {
       public State1(StateFactory factory, IStateUser context)
                : base(factory, context)
       {
       }
    
       public override void MoveNext()
       {
          TransitionTo<State2>(() => new State2(_factory, _context));
       }
    
       public override void MovePrevious()
       {
          throw new InvalidOperationException();
       }
    }
    
    public class State2 : State
    {
       public State2(StateFactory factory, IStateUser context)
                : base(factory, context)
       {
       }
    
       public override void MoveNext()
       {
          TransitionTo<State3>(() => new State3(_factory, _context)); //State 3 is omitted for brevity
       }
    
       public override void MovePrevious()
       {
          TransitionTo<State1>(() => new State1(_factory, _context));
       }
    }
    
    public interface IStateUser
    {
       State CurrentState { get; set; }
    }
    
    public class Client : IStateUser
    {
    
       public Client()
       {
          var factory = new StateFactory();
          var first = new State1(factory, this);
          CurrentState = factory.GetOrCreate<State1>(() => first);
       }
    
       public void MethodThatCausesTransitionToNextState()
       {
          CurrentState.MoveNext();
       }
    
       public void MethodThatCausesTransitionToPreviousState()
       {
          CurrentState.MovePrevious();
       }
    
       public State CurrentState
       {
          get;
          set;
       }
    }
    
    public class StateFactory
    {
        private Dictionary<string, State> _states = new Dictionary<string, State>();
    
        public State GetOrCreate<T>(Func<T> creator) where T : State
        {
            string typeName = typeof(T).FullName;
    
            if (_states.ContainsKey(typeName))
                return _states[typeName];
    
            T state = creator();
            _states.Add(typeName, state);
    
            return state;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've used the State pattern to implement a simple finite state machine. Looking at
Consider this code... using System.Threading; //... Timer someWork = new Timer( delegate(object state) {
This is getting little bit tricky. I am using state pattern in my application
The application I'm currently writing is using MVVM with the ViewModel-first pattern. I have
I'm currently working on a legacy system using Oracle's ADF Faces JSF implementation for
Question: I'm new to the repository pattern, and I'm attempting to implement a new
I am trying to implement the command pattern to control a robot. I'm using
What are some common strategies for refactoring large state-only objects? I am working on
I have a working solution in java using a classic state design pattern and
I'm trying to implement the APM pattern using Richter's AsyncEnumerator class. The goal is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.