-1

I wanted to check if User exists or not in the database, and i take a User object and check if it is null or not.But the problem is in my code if user doen't exist in our database it returns following exception,

Object reference not set to an instance of an object.

I know this error happen when there is no such a user in our database.So.. i wanted to know if this user object( i want to return null or not) null or not.

My Part of Code

  if(newsManager.GetUserUsingEmail(User.Email).Email != null) //If user doesn't exists this come the above mentioned exception
    {
        //User Exists
    }
    else
    {
       //User Doesn't exists
    }

How to solve it ?

Gianmarco
  • 2,536
  • 25
  • 57
TechGuy
  • 4,298
  • 15
  • 56
  • 87

3 Answers3

2

The null reference exception is probably due to you trying to access the Email property on the user returned from the GetUserUsingEmail method. You should test if the returned value is null first and only then try accessing properties on it.

var user = newsManager.GetUserUsingEmail(User.Email);
if (user != null)
{
     // user exists
}
else
{
    // user does not exist
}
christophano
  • 915
  • 2
  • 20
  • 29
  • I think this has the best code structure of the answers presented where the statement `GetUserUsingEmail()` is not repeated. –  Jul 19 '15 at 23:52
0

if newsManager.GetUserUsingEmail(User.Email) returns null, then you will agree that attempting to invoke .Email should give you the Object reference not set to an instance of an object. error, right?

As suggested in the comments, if your condition is truly just checking to see if the user exists or not, then simply do this:

if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
    //User Exists
}
else
{
    //User Doesn't exists
}

If, as your code suggests, your intent is really to enter the if block only if you have a valid Email value for a valid user, then you can do that like this instead:

var user = newsManager.GetUserUsingEmail(User.Email);
if(user != null && !string.IsNullOrEmpty(user.Email))
{
    //User Exists and has a valid email
}
else
{
    //User Doesn't exists or doesn't have a valid email.
}
sstan
  • 35,425
  • 6
  • 48
  • 66
0

You cannot get property from null. Check object != null instead:

if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
    {
        //User Exists
    }
    else
    {
       //User Doesn't exists
    }

In C# 6.0 you can use Safe Navigation Operator (?.):

 if(newsManager.GetUserUsingEmail(User.Email)?.Email != null) //If user doesn't exists this come the above mentioned exception
    {
        //User Exists
    }
    else
    {
       //User Doesn't exists
    }
Lokki
  • 372
  • 1
  • 6
  • 20