In .NET 4.x and above versions, use Null-Coalescing operator
?? to prevent an exception, as shown below:In the above example,
?? is a null coalescing operator that checks if an object is null or not, if it is null then create an object. The cities ?? new List<string>() creates a new list object if a cities is null in foreach loop. Thus, the NullReferenceException will be not be raised.💬 Like this note? Want to support the channel? Become a patron: https://www.patreon.com/csharp1001notes