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?
5
Answers
Try this:
Or, better way to do the same:
When you just return
null
that means, your Task isnull
, not result of async method.You call await on null. I think you had something like this in mind:
Yes, you are using the object. The object that is
null
is theTask<DateTime?>
you return fromGetUserBirthDayAsync()
. And you use it when you try toawait
this task.So the
NullReferenceException
is raised by theawait
(or the code the compiler creates for it).So what you probably want to do is to return a
Task<DateTime?>
that returns anull
as result type:An alternative could be to just use the
Task.FromResult<DateTime?>(null)
as.
MSDN Documentation
Pretty much the same as the other options but IMHO it looks much cleaner.
You could also make the method async