ash
ash

Reputation: 3085

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

I have an interface for all social network services. Most of them are async task methods.

For Twitter implementation, since Twitter does not provide user birthdays through its REST API, wanted to return null.

The interface method GetUserBirthDayAsync is implemented as follows for the 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();

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 error occurred in setting the value for the birthdate variable.

What is happening? What is causing the exception?

Upvotes: 5

Views: 9695

Answers (5)

OD1995
OD1995

Reputation: 1777

You could also make the method async

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

Upvotes: 0

Backs
Backs

Reputation: 24913

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.

Upvotes: 9

Nico
Nico

Reputation: 12683

An alternative could be to just use the Task.FromResult<DateTime?>(null)

as.

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

MSDN Documentation

Creates a Task that's completed successfully with the specified result.

Pretty much the same as the other options but IMHO it looks much cleaner.

Upvotes: 5

michauzo
michauzo

Reputation: 356

You call await on null. I think you had something like this in mind:

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

Upvotes: 1

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43916

even though am not using the object

Yes, you are using the object. The object that is null is the Task<DateTime?> you return from GetUserBirthDayAsync(). And you use it when you try to await this task.

So the NullReferenceException is raised by the await (or the code the compiler creates for it).

So what you probably want to do is to return a Task<DateTime?> that returns a null as result type:

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

Upvotes: 2

Related Questions