HomeCSharpC# Error CS1994 – The ‘async’ modifier can only be used in methods that have a body.

C# Error CS1994 – The ‘async’ modifier can only be used in methods that have a body.

C# Error

CS1994 – The ‘async’ modifier can only be used in methods that have a body.

Reason for the Error & Solution

The ‘async’ modifier can only be used in methods that have a body.

Example

The following sample generates CS1994:

interface IInterface
{
    async void F();
}

To correct this error

A non-concrete method declaration in an interface declaration has no method body. In order to support the async modifier, the compiler subsumes the method body logic in a state machine. Without a method body, the compiler cannot emit this state machine. In addition, the logic of a method body must contain an await operator to signify a continuation the state machine must manage. Without that await operator, a state machine has nothing to manage.

In the case of a non-concrete method, if deferring the implementation of a method body to a class that implements the interface, simply removing the async modifier will correct the error:

interface IInterface
{
    void F();
}

Alternatively, a concrete default method (introduced in C# 8.0) could be declared within the interface:

interface IInterface
{
    async void F()
    {
        await Task.Run(() =>
        {
            /* do something useful*/
        });
    }
}

Leave A Reply

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

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...