In a previous article I talked about the yield operator. Today, I want to talk about another one of my favorite features in the C# language. The null coalescing operator. How many times have you written a block of code similar to the one below which checks for a null value and formats some output based on the result.
if( searchResult == null ) txtResults.Text = String.Empty; else txtResults.Text = searchResult; The null coalescing operator can help you streamline your code. Using the null coalescing operator you can turn that block of code into this:
txtResults.Text = searchResult ?? String.Empty;
Basically the "??" means that if the searchResult is null then return String.Empty else return the searchResult. The "??" operator works with value types and reference types. Therefore we could also use this on integers. Here is an example: int? number = null; int result = number ?? 0;
In case you did not know, a single question mark (i.e. int? number) after the int allows you to assign a null value to the integer variable. This is important for technologies like LINQ to SQL. For example, lets say you are designing a table in SQL Server to track statistics. In one of your tables you create a column called MaxHits. The column is created as a integer but you want to allow null values. When you drag the table into the design surface of Visual Studio to generate the database code you would end up with a variable called MaxHits with a datatype of int?. If you had a primary key on the table called ID then a regular int would be used because you would not allow null values for that field.