From the course: Visual Studio Developer Tips

Unlock this course with a free trial

Join today to access over 22,400 courses taught by industry experts.

Null propagation

Null propagation

- [Instructor] How many times have you run into an unexpected null reference exception when you're working in .NET, or C# or Visual Basic? It happens more often than it should, at least it does in my case. So the tip that I want to look at today is a language feature that debuted in C# 6 called the null propagation operator. And here's how it works. Here's the situation you use it in. On line 16, I have a variable of type tour, that's set to null, and then on line 18, I have a string variable. What I'd like to do on line 26 is get the tourName property and store that in this string variable. Because tour1 is null, this line of code will throw an exception. We typically will write code like this to protect ourselves. We'll write a no-statement that says, if tour1 equal equal the null, then return. That's sometimes called a guard clause. Using the null propagation operator, we can reduce some of that. So first let me comment this out, Control + K, Control + C. Instead, what we'll do…

Contents