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 imagehelp@codebetter.com
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
{
get
{
if (service == null)
return service = LazyLoadSomeService();
else
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

[Advertisement]

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)