Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference not set to an instance of an object when calling asynchronous method

Tags:

c#

Twitter does not provide user Birthdays through its REST API. Because of that, I prepared a nullable DateTime property.

I also prepared an Interface for all social network services. Most of them are async Task methods.

But I can't get to pass this error: Object reference not set to an instance of an object even though I'm not using the object.

The Interface method GetUserBirthDayAsync is implemented as follow for Twitter service:

public Task<DateTime?> GetUserBirthDayAsync(){
    return null; // because twitter does not provide user birthday
}

and this is how I used the method:

DateTime? BirthDate = await socialNetworkService.GetUserBirthDayAsync();

The error occurred in setting the value to the BirthDate variable.

What is happening? What is causing the exception?

like image 364
ash Avatar asked Dec 05 '22 00:12

ash


1 Answers

Try this:

public Task<DateTime?> GetUserBirthDayAsync()
{
    return Task.Run(() => (DateTime?)null);
}

Or, better way to do the same:

public Task<DateTime?> GetUserBirthDayAsync()
{
    return Task.FromResult<DateTime?>(null);
}

When you just return null that means, your Task is null, not result of async method.

like image 136
Backs Avatar answered May 04 '23 01:05

Backs