'C#: Simple state machine, how to get state from database and assing it?

I am wondering how to assign a loaded state from a database to a state machine.

Simple example IState interface:

public interface IState
{
    void Process(MyClass obj);
}

We got 3 possible states: New, Modified and Finished:

public class StateNew : IState
{
    public void Process(MyClass obj)
    {
        // processing stuff
        obj.State = new StateModified();
    }
}

public class StateModified : IState
{
    public void Process(MyClass obj)
    {
        // processing stuff
        obj.State = new StateFinished();
    }
}

public class StateFinished : IState
{
    public void Process(MyClass obj)
    {
        // processing stuff
    }
}

Then, our class:

public class MyClass
{
    private IState _state;
    public IState State
    {
            get { return _state; }
            set
            {
                _state = value;
            }
    }

    public MyClass()
    {
        _state = new StateNew();
    }

    public void Process() => State.Process(this);
}

So, we deal with the class and then, we save it to the database saving in the "state field" the value "xxx.StateModified" that _state.ToString() provided us.

The show must go on so the moment of loading the object from the database has arrived, and the database says that state field is xxx.StateModified.

In 2022, with C# v10 available and C# v11 incoming, there has to be a better approach to this that making up a constructor with a switch:

public MyClass(string? stateName = "StateNew")
{
        switch (stateName)
        {
            case "StateModified":
                State = new StateModified();
                break;

            case "StateFinished":
                State = new StateFinished();
                break;

            default:
                State = new StateNew();
                break;
        }
}

:(((((



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source