0

Hello everyone today I was working to make API.I got confused when I saw different behavior of C# compiler. let me explain:

I get exception:

If(userLoginModel.UserId>0)
{
//do something
}
else{
//do something
}

Exception: {"Object reference not set to an instance of an object."}

Yes it is null; But if write :

if (userLoginReturnModel != null && userLoginReturnModel.UserId >0)
{
//do something
}
else
{
//do something
}

This code did not throw any Exception.

Note: My question is why compiler is not throwing any exception on 2nd code because there is && condition in if so when compiler will check that userLoginReturnModel.userId > 0 then this will also need to throw exception because object is null. And as we know that both condition will be check in if. Any answer with good explanation.

Wajid khan
  • 842
  • 9
  • 18

2 Answers2

7

In case of:

if (userLoginReturnModel != null && userLoginReturnModel.UserId >0)

if the first condition is false then next is not checked (because there is no need to do so - false && anything gives false).

Similiar with || - if first is true then next are not checked (no need - true || anything gives true).

Piotr Wojsa
  • 938
  • 8
  • 22
  • 3
    Maybe as a appendix: the expection would occur, when only concating the bool confitions with one "&". Check: https://stackoverflow.com/questions/5537607/usage-of-versus – Malior Jan 10 '19 at 07:58
2

in this case if userLoginReturnModel is null you will have:

if ( false && ...

do you need to check conditions after false? False && true is still false. so rest of conditions doesn't matter and will not be checked.

Pablo notPicasso
  • 3,031
  • 3
  • 17
  • 22