Null Conditional - ?. operator MSDN
Null conditional sounds an awful lot like Null Coalescence now doesn't it? Null Conditionals work in much the same way, by first checking the value of the left side of the operator for null. First, here is an example of getting a property from an object without knowing it is null using the longhand method, then another with Null Conditionals, and finally a little trick that I'll explain below.
The above Null Conditional code with check if User is null, and, if it's not, returns the ID property. If it is null, it will simply return null. This stops the dreaded Null Exception error that we all hate to see, and makes your code much easier to read and understand!
What if you don't want null returned by the Null Conditional? Well, there's a simple trick for that as well. Combining a Null Conditional with it's cousin, Null Coalescence, you get back whatever default you want! See the third line of code above for how it's done.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int? x = User != null ? User.ID : null; //standard null checking | |
int? y = User?.ID; //null conditional, wowie | |
int z = User?.ID ?? Guid.NewGuid(); //null conditional coupled with null coalenscence |
What if you don't want null returned by the Null Conditional? Well, there's a simple trick for that as well. Combining a Null Conditional with it's cousin, Null Coalescence, you get back whatever default you want! See the third line of code above for how it's done.
String Interpolation - $"{x}" MSDN
String Interpolation is the act of injecting variables into a string without having to close the string constant and manually concatenate variables into it. An example of a traditional string concatenation is as follows:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var x = "Example"; | |
Console.WriteLine("A simple " + x + " string."); |
Not too pretty, right? Here is the same example with String Interpolation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var x = "Example"; | |
Console.WriteLine($"A simple {x} string"); |
There we go! Much easier to read! Simple to use, simple to understand, simple to read.