C# null coalescing operator

Posted by: Clarity Blogs: ASP.NET, on 18 Aug 2006 | View original

I have a new favorite feature in VS 2005 - the null coalescing operator: ??

This is a short cut for checking if a value is null and if so returning the value of the second operand.  The syntax is as follows:  string newVal = myVal ?? "default";

The first operand (myVal) must be a nullable type (in this case a string).  This evaluates as: if myVal is not null then set newVal to the value of myVal, otherwise set newVal to the value of the string "default".  This can be used inline as well such as: 

string newVal = "My data value contained a value of " + (myVal ?? "null") + ".";

Now you don't have to do any explicit if/then conditionals to check for nulls before assigning a value which is a great short cut.  Remember though to be consistent - if your development team has a standards guide (which I'd recommend they do) then decide if this will become your teams preferred way of dealing with null checks.  It gets to be cluttered code if you have half a team of developers using the coalescing operator and another half still writing out if/then condition checks.

Share this post: Email it! | bookmark it! | digg it! | reddit!

Advertisement

Similar Posts

  • Is The Null Coalescing Operator Thread Safe? more
  • Tiny Trick For ViewState Backed Properties more
  • Double-Checked Again. The way to do it. more
  • Oracle Database ASP.NET 2.0 Provider Schema : Work In Progress more
  • Extending dynamic sorting of objects using lightweight code generation. more
  • Programming Visual CSharp 2005 more
  • Double-Checked Again. The way to do it. more
  • Operator Overloading in VB 2005 more
  • Module Performance Enhancements more
  • How to load a DSL domain model instance file programmatically more

News Categories

.NET | ADO.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Community Server | dasBlog | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD