简体   繁体   中英

c# Object reference not set to an instance of an object

I'm trying to work out if something does not exist in the table. I'm telling it to see if the UserInfo contains information for user .

UserInfo Character = db.UserInfoes.SingleOrDefault(a => a.Username == user);
if (Character.Username == null || Character.Username.Length == 0)
{
    //do stuff
}

But I get an error on the if statement.

Object reference not set to an instance of an object.

It seems that the db.UserInfoes.SingleOrDefault(a => a.Username == user) expression returned null because it didn't find any matching records that satisfy the filter criteria.

so:

UserInfo Character = db.UserInfoes.SingleOrDefault(a => a.Username == user);
if (Character == null || Character.Username == null || Character.Username.Length == 0)
{
    //do stuff
}

You wrote in the comments that you know that db.UserInfoes.SingleOrDefault(a => a.Username == user) returned null. Hence, Character is null and you need to check this case separately:

if (Character == null ||                 // this line is new
    Character.Username == null || 
    Character.Username.Length == 0) 
{ 
    //do stuff 
} 

Since you say the error occurs on the if statement, Character is null . You need to add a check for if (Character == null) .

If you are getting an error on the if statement, then it is likely that your search:-

UserInfo Character = db.UserInfoes.SingleOrDefault(a => a.Username == user);

Has not found any record matching where Username equals user . When that happens, the value of Character is null .

Your issue is that you are trying to call a property on something that doesn't exist. You need to perform a check to ensure that Character is not null before calling any of its members.

if ( Character != null ) 
{
   // Can now safely call properties on the Character object
}
else
{
   // Take the appropriate action for circumstances where we can't
   // find a user by username
}

First you should check whether Character is null, then later you should check for remaining in Character.

if(Character != null)
{
   if(Character.Username == null || Character.Username.Lenght == 0)
   {
       //Do Stuff
   }
}

EDIT:

or simply you can check only the Character, like

if(Character == null)
{
//Do Stuff
}

You need to add a test on Character to know if it's null. If that's the case, you'll have the exception you mentionned.

So just do this :

if(Character != null)
{
    //Your code can now safely call the Properties/Methods/etcetc...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM