HomeCSharpC# 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‘?

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...