C# Error CS1997 – Since ‘{0}’ is an async method that returns ‘Task’, a return keyword must not be followed by an object expression. Did you intend to return ‘Task‘?

C# Error

CS1997 – Since ‘{0}’ is an async method that returns ‘Task’, a return keyword must not be followed by an object expression. Did you intend to return ‘Task‘?

Reason for the Error & Solution

Since is an async method that returns Task, a return keyword must not be followed by an object expression. Did you intend to return Task<T>?

Example

The following sample generates CS1997:

using System.Threading.Tasks;
class C
{
    public static async Task F1()
    {
        return await Task.Factory.StartNew(() => 1);
    }
}

To correct this error

A return statement in an async method returns the result of an awaitable statement. If the awaitable statement does not have a result, the state machine emitted by the compiler encapsulates returning the non-generic Task, eliminating the need for a return statement. Encountering error CS1995 means the referenced code includes a return statement that conflicts with the async modifier and the method’s return type. The error indicates that the current method’s implementation does not align with its initial intent. The simplest way to correct the error is to remove the return statement:

    public static async Task F1()
    {
        await Task.Factory.StartNew(() => 1);
    }

But, the resulting implementation no longer needs the async modifier or the await operator. A more accurate way of correcting this error is not to remove the return statement, but to remove the async modifier and the await operator:

    public static Task F1()
    {
        return Task.Factory.StartNew(() => 1);
    }

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...