C# null coalescing operator

Posted by: Clarity Blogs: ASP.NET, on 18 Aug 2006 | View original | Bookmarked: 0 time(s)

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!

Category: C# | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 7073 | Hits: 70

Similar Posts

  • Filtering with string parameter that allows free user input more
  • Adding Syntactic Sugar to the Spark View Engine more
  • An Extensive Examination of LINQ: Grouping and Joining Data more
  • Major changes in RadNumericUpDown for Silverlight and WPF more
  • System.Data.Linq.Binary is not XmlSerializable more
  • The Law of Demeter Is Not A Dot Counting Exercise more
  • An Extensive Examination of LINQ: The Standard Query Operators more
  • ASP.NET Grid Tip: How To Check For Empty Values In Header Filter more
  • SharePoint Development Best Practices (Summary) more
  • Null Object design pattern instead of returning null more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | 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