Reputation: 17373
I've a code below:
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address address { get; set; }
public Person GetFullName()
{
return new Person { };
}
}
public class Address
{
public int Name { get; set; }
}
I need to check if Person is not null and also the Address it contains. For this the code below works:
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.FirstName="bla";
if (person != null && person.address != null)
{
Console.WriteLine(person.address.Name);
}
}
}
Question I've:
How does this code executed as person.Address should have thrown Null Exception?
if (person != null && person.address != null)
Upvotes: 0
Views: 179
Reputation: 5823
The correct way to check for nullity is if(person != null)
. If you do if(!person.Equals(null))
then you will get a NullReferenceException if person == null
. Which is kind of comical since avoiding this exception was the goal in the first place.
Your code executes because if person != null
is true only then it starts looking at the next statement wich is person.address != null
. if the first statement returns false, it won't even look at the next because of the && operator.
Edit: you also might wanna know that person.address.Name
is never null since this is an integer. By default it's value = 0 instead of null. Of course, this applies only to class members fields, as local method-level fields must be explicitly assigned a value before use.
Upvotes: 1
Reputation: 137148
Your code is perfectly fine
if (person != null && person.address != null)
works when person
is null because C# terminates the evaluation of the statements in the expression as soon as it comes across one that evaluates to false.
Your code is the same as the following:
if (person != null)
{
if (person.address != null)
{
// do stuff
}
}
Other languages (Ada) aren't the same. There the order the expressions are evaluated is either not determined or determined by the "cost" of the operation. There if you want to force the order of evaluation you have to use the and then
(or or else
) construct:
if (person != null and then person.address != null)
It makes the code clearer but that's about all it has going for it.
Upvotes: 3