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)
Your code is perfectly fine
works when
personis 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:
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(oror else) construct:It makes the code clearer but that’s about all it has going for it.