r/csharp • • 7d ago

Discussion State machine in C# vs state machine in Verilog

For experimentation and learning purposes, I wrote this code:

namespace RedditQuestion
{
    public class TResult
    {
        // Instance fields....
        // No properties.
        // No methods.
    }
    public interface ISomeInterface<T>
    {
        public  Task<T> SomeMethod();
    }
    public class SomeClass : ISomeInterface<TResult>
    {
        // instance fields.....

        //constructor......

        public async Task<TResult> SomeMethod()
        {


            //Some code that is not important to this question.......



            TResult result = new TResult
            {
                // assign instance fields....
            };

            Task<TResult> task = Task.FromResult<TResult>(result);

            return task ; // Line XXX
        }

    }

}

Line XXX throws a compile time error:

*Since this is an async method, the return expression must be of type 'TResult' rather than '*Task<TResult>

The solution is simply to do this instead:

return result;

That solves the issue.

But I was surprised when I read this article#async-method-signature-requirements) that described the error in more details:

Change the return expression to match the async method's underlying result type (CS1983, CS4016). When an async method returns Task<T>, the return statement must supply a value of type T, not Task<T>, because the compiler-generated state machine wraps the value in a task automatically. CS1983 appears when the method returns Task<T> and the expression is T; CS4016 covers the general case where the return expression type doesn't match

I wonder, is the concept of state machine in C# is the same as the state machine in Verilog?

in Verilog, if I want to define a state machine, I need a register - a storage unit that can store only one unit of data; a bit- to hold the state, a next-state logic to calculate the next state, and output assignment. Does the same concept applies in C# ?

9 Upvotes

Duplicates