Thursday, November 8, 2007
The C# ?, ?: and ?? operators
Most programmers are familar with the ternary or conditional assigment (
The example above is a short-hand equivalent of the following C# code.
But, when it comes to C#.NET 2.0 or later, there is an even quicker shorthand if the programmer wants to make conditional assigmnets on null. Enter the null assignment(
If the left hand side of the
One caveat to this is that
In addition to the ternary (
As a .NET programmer, you are no doubt familar with value types verses reference types. Reference types can generally be null, or contain a reference to an instance of an object. Value types such as
?:) operator. This is by no means unique to C#, as similar operators exist in most modern programming languages. The previous posting entitled "String concatentation and null" included an example of one:
string myString = (someVariable != null) ? someVariable : "";
The example above is a short-hand equivalent of the following C# code.
string myString;
if (someVariable != null)
{
myString = someVariable;
}
else
{
myString = "";
}
But, when it comes to C#.NET 2.0 or later, there is an even quicker shorthand if the programmer wants to make conditional assigmnets on null. Enter the null assignment(
??) operator. The following example is equivalent to the two examples above.
string myString = someVariable ?? "";
If the left hand side of the
?? operator (i.e. someVariable) is not null, then it is assigned as the value. But, if the left hand side of the operator is null, then the right hand side or the operator is assigned as the value.One caveat to this is that
someVariable is only evaluated once. This is not suprising, as it is only listed once. But, it does differ from the other two examples in which someVariable is evaluated twice: once for the condition, and once for the assignment. This is not likely to cause many problems, but is something to keep in mind if you were calling someMethod() instead of someVariable because it means the code is not necessarily a 100% compatible replacement for the earlier two examples.In addition to the ternary (
?:) and null assignment (??) operators, there is also a third way to use the question mark in C#.NET 2.0 and later. Enter the nullable type (?) operator!As a .NET programmer, you are no doubt familar with value types verses reference types. Reference types can generally be null, or contain a reference to an instance of an object. Value types such as
ints, on the other hand, cannot traditionally be null. The nullable type operator allows value types to be null, or any valid value! You can specify a type is nullable by putting a question mark after the type.
int nonNullableInt = 0;
int? nullableInt = null;
Subscribe to Posts [Atom]