Bookmark and Share

Null Coalescing Assignment Operator for C# 5

If you read my article on the null coalescing operator (??), you’ve probably got a good idea on how useful it is. It makes your code more declarative, which makes it easier to read. But I find one thing disappointing about it, which I hope can be corrected in C# 5 with the introduction of a new operator.

One way to use the null coalescing operator is by checking a variable against itself, and if it’s null assign another value. Besides eliminating imperative code, this is great when combined with factory methods.

client.WorkOrder = client.WorkOrder ?? WorkOrder.Create();

My complaint is that you have to declare the same value on the left and right side. It’s not much, but it’s easily corrected. Due to C#’s C-based heritage, other types of assignment operators, called compound assignment operators, already exist: +=, –+, *=, /=, %=, &=, |=, ^=, <<=, and >>=. These work as if you had broken them apart. In other words, x += y is the same as x = x + y. There are two differences: the left operand isn’t repeated and the C# compiler evaluates the left operand once with the compound assignment operator.

I propose a new compound operator for C# 5: the null coalescing operator. The symbol for it would logically be ??=. It will simplify our code when working in a declarative manner.

client.WorkOrder ??= WorkOrder.Create();

It doesn’t require a framework change as the IL generated by compound assignment operators is the same as their analogues. It’s a compiler change, and I don’t believe it would be a difficult one at that.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.