The C# Null-Coalescing operator or the ?? operator is a binary operator that returns the left-hand operand if it is not null; otherwise it returns the right operand. It can be used with both nullable and reference types.
Here’s a simple example of using the Null-Coalescing operatorint? i = null; int j = i ?? 2; // here the resultant value of j is 2Here are some additional ways of using the Null-Coalescing operator in your code.
Method 1
string address = homeAddress1 ?? homeAddress2 ?? officeAddress ?? "No Address";returns the first non-null value in this long expression. This expression returns “No Address” if homeAddress1, homeAddress2 and officeAddress are Null.
Method 2
While converting a Nullable Type to Non-Nullable type, we do an explicit cast to avoid assigning null values to a non-nullable type, as shown below:
int? a = NullType(); // returns nullable int int b = (int)a;instead you can avoid the explicit cast using a null-coalescing operator and write:
int? a = NullType(); int b = a ?? 0;
Method 3
private IList<Person> person; public IList<Person> PersonList { get { return person ?? (person = new List<Person>()); } }Typical usage of the null-coalescing operator in a lazy instantiated private variable.
Method 4
string conn = Connection["TestMachineStr1"] ?? AppConnection["ProdMachineStr2"] ?? DefaultConnection[" DefaultConn"];
Note: The Null-Coalescing operator is useful but may sometimes be an overkill, especially when developers use it to flaunt their coding skills. I sometimes choose ‘understandable code’ over ‘terse code’, focusing on the intent.
Feel free to use the comments section to demonstrate how you have used the null-coalescing operator in your projects.
No comments:
Post a Comment