Null Coalescing Assignment Operator for C# 5

by KodefuGuru 7. January 2010 16:53

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.

Tags: , ,

Kodefu

Comments

1/7/2010 11:05:19 PM #

robby valles

i can see this working Laughing

robby valles United States

1/8/2010 2:54:10 AM #

Urs Enzler

Yes, I miss that, too.

Urs Enzler Switzerland

1/8/2010 4:25:20 AM #

caspar kleijne

I guess this is impossible since C# classes use reference semantics. (instead of C++ that uses value semantics)

Left hand is a is always a reference right hand is the object. not vice versa.

In your case the compiler should be aware of that the left hand is both a reference AND value?? That is not the C# way.

actually:
List<string> blap = null; // LH reference to a RH null value
List<string> blap = blap ?? new List<string>() //LH reference , blap omn RH is NOT a reference but a value/object, just as new List<... is.

caspar kleijne Netherlands

1/8/2010 5:30:03 AM #

zproxy

i miss operator ??= too!

zproxy Estonia

1/8/2010 6:29:56 AM #

wise

I liked your post.It's very informative.

wise United States

1/8/2010 12:56:32 PM #

Chris Marisic

I agree, I'd like to see the null coalescing assignment operator also.

FYI there is a work around that you can use currently. It's a rather uncommonly known fact that the assignment operator itself actually returns the assignee.

So you can do this inside your object

public WorkOrder WorkOrder  {
get { return (WorkOrder) _myWorkOrder ?? (_myWorkOrder = WorkOrder.Create()) }
}

I tend to do this alot with properties that use generic collections if i don't initialize them in the constructor, and with properties that wrap the Session/Cache/ViewState bags so I don't have to worry about null reference issues

Chris Marisic United States

1/8/2010 1:05:10 PM #

chris

That's cool! I didn't realize you could do that, thanks. Out of curiosity, why are you casting there?

chris United States

1/8/2010 1:05:52 PM #

Guy Ellis

Yes - would love this feature. Lobby congress (or MS).

Guy Ellis United States

1/8/2010 1:57:49 PM #

brad dunbar

I love this.  This, along with the ternary operator, has long been one of my favorite C# features (VB's 'IIf' is a nightmare, and has no '??').  With the addition of LINQ C# has become very declarative and '??' helps a ton.

brad dunbar United States

1/8/2010 7:43:20 PM #

Robert Friberg

I would also like to see this feature, but it has probably been left out for some reason,  difficulty of implementation not being one of them. The language designers must have considered ??= at some point. I find it very unlikely that they never even gave it a thought.

@caspar: Your reasoning is flawed. A ??= B is just a shorthand notation of A = A ?? B, if the latter is valid, which it is, so is the former. The parser associates each variable with some logical memory adress holding the content of the variable. When assigned to (LHS), the memory is written, when used in an expression the memory is read. In this sense there is no difference between a reference type and a value type.

Robert Friberg Sweden

1/21/2010 2:26:26 AM #

trophy melbourne

In your case the compiler should be aware of that the left hand is both a reference AND value?? That is not the C# way.

trophy melbourne United States

1/22/2010 12:55:56 AM #

Noritake

I tend to do this alot with properties that use generic collections if i don't initialize them in the constructor, and with properties that wrap the Session/Cache/ViewState bags so I don't have to worry about null reference issues

Noritake United States

2/11/2010 5:10:00 AM #

conversion analysis

I really don't initialize in the constructor...nice feature thanks...

conversion analysis India

3/10/2010 7:59:40 AM #

Car Mats

Its informative Post.i also want this tool.

Car Mats United States

3/10/2010 11:23:25 PM #

Noritake

FYI there is a work around that you can use currently. It's a rather uncommonly known fact that the assignment operator itself actually returns the assignee.

Noritake India

3/11/2010 12:13:17 AM #

Newbury Park Real Estate

I don't initialize them in the constructor, and with properties that wrap the Session/Cache/View State bags so I don't have to worry about null reference issues

Newbury Park Real Estate India

3/11/2010 12:44:10 AM #

Country Home for Rent in Umbria Italy

Out of curiosity, why are you casting there? that is unique and Beninese.

Country Home for Rent in Umbria Italy India

3/11/2010 1:04:11 AM #

small business seo services

I don't initialize them in the constructor, and with properties that wrap the Session/Cache/ViewState bags so I don't have to worry about null reference issues

small business seo services India

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

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

© Copyright 2010