Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

 public async Task<Data> GetData()
    {
        Task<Data> data = null;

        //This data will be fetched from DB
        Data obj = new Data();
        obj.ID = 1;
        obj.Name = "Test";

        //Need to 
        // data = obj;

        return Task.Run(() =>
        {
            return obj;
        });

    }

Error 1 Since this is an async method, the return expression must be of type 'WebApplication2.Data' rather than 'Task' \inb-fs01\Users\user\Visual Studio 2012\Projects\WebApplication2\WebApplication2\Home.aspx.cs 35 20 WebApplication2

Can someone help me sorting out this issue?

like image 824
Ramesh Avatar asked Sep 10 '15 10:09

Ramesh


People also ask

What is the return type for async method?

Async methods have three possible return types: Task<TResult>, Task, and void. In Visual Basic, the void return type is written as a Sub procedure. For more information about async methods, see Asynchronous Programming with Async and Await (Visual Basic).

Is an async method that returns task?

Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.

Is an async method that returns task a return keyword must not be followed by an object?

DoSomething()' 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>'?

What is the base return type for async methods C#?

The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.


1 Answers

Where ever u are calling this function, try to put await before that call, like below:

Data obj = await GetData();

And return Data object simply from GetData() method.

like image 141
Awn Ali Avatar answered Sep 19 '22 05:09

Awn Ali