Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at
C# 4.0 Feature Request: "??=" the Lazy load operator...

A cool C# 2.0 feature is the "??" coalesce operator, which lets you do this:

public ISomeService Service
get { return service = service ?? LazyLoadSomeService(); }

For the noobs, this code is equivalent to this:

public ISomeService Service
get { return service = service == null ? LazyLoadSomeService() : service; }

Which is the same as:

public ISomeService Service
if (service == null)
return service = LazyLoadSomeService();
return service;

Now it would be great if we could trim this up just a little bit more...

public ISomeService Service
get { return service ??= LazyLoadSomeService(); }

This is similar to +=, *=, and family. This seems like the logical progression to me. I guess this would be called "coalescing assignment operator" or something like that. And we could take this one step even further... C# 3.0 has Automatic properties that alleviates the need for an explicitly declared backing field. What happens when my suggested "coalescing assignment operator" and automatic properties do the nasty...

public ISomeService Service
get?? { LazyLoadSomeService(); }

The syntax is debatable but I think the concept is nice and useful.

Posted 10-26-2007 7:06 PM by Jim Bolla


About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)