skip to Main Content

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


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

    Login or Signup to reply.
  2. 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
    }
    
    Login or Signup to reply.
  3. 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);
    }
    
    Login or Signup to reply.
  4. 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.

    Login or Signup to reply.
  5. You could also make the method async

    public async Task<DateTime?> GetUserBirthDayAsync(){
        return null; // because twitter does not provide user birthday
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search