Avoiding NullReferenceExceptions C# with Example



Avoiding NullReferenceExceptions C# with Example

var person = new Person 
{ 
Address = null; 
}; 
var city = person.Address.City; //throws  a  NullReferenceException 
var nullableCity = person.Address?.City; //returns the value of null 
This effect can be chained together: 
var person = new Person 
{ 
Address = new Address 
{ 
State = new State 
{ 
Country = null 
} 
} 
}; 
// this will always return a value of at least "null" to be stored instead 
// of throwing a NullReferenceException 
var countryName = person?.Address?.State?.Country?.Name; 

0 Comment's

Comment Form

Submit Comment