The following code will throw a NullReferenceException if the variable “text” being passed in is null. You can’t call ToUpper() on a null string.
You can also have null reference exceptions because any type of object is null.
public void MyMethod(string text) { //Throws exception if text == null if (text.ToUpper() == "Hello World") { //do something } }
You can also have null reference exceptions because any type of object is null.
SqlCommand command = null; //Exception! Object reference not set to an instance of an object command.ExecuteNonQuery();
Use the Null Conditional Operator to Avoid NullReferenceExceptions
text?.ToUpper(); //from previous example, would return null int? length = customerList?.Length; // null if customerList is null Customer first = customerList?[0]; // null if customerList is null int? count = customerList?[0]?.Orders?.Count(); // null if customerList, the first customer, or Orders is null
Use Null Coalescing to Avoid NullReferenceExceptions
The following code throws an exception without the null coalescing. Adding “?? new List<string>()” prevents the “Object reference not set to an instance of an object” exception.
List<string> values = null; foreach (var value in values ?? new List<string>()) { Console.WriteLine(value); }
No comments:
Post a Comment