Navigation
Links

Powered by Squarespace
« yield return “elegant code” | Main | Not going to the PDC »
Saturday
Aug272005

ISNULL in c#

If you’ve used SQL Server, you’ve probably used the ISNULL function. It replaces NULL with the specified replacement value. In .NET 2.0, c# gets this capability with a new ?? operator – the null coalescing operator. So when you define nullable types, you can check for null, and replace it with another value with this simple syntax:
int? x = 5;
int? y = null;
// since x is not null, (x ?? 0) returns 5.
Assert.AreEqual(5, (x ?? 0));
// since y is null, (y ?? 0) returns 0.
Assert.AreEqual(0, (y ?? 0));
The operator also works with reference types:
// table can be null
public static int Fill(DataTable table)
{
// if table is null, _defaultDataTable is used instead
foreach(DataRow dataRow in table.Rows ?? _defaultDataTable.Rows)
{
// do work
}
return 0;
}

Video presentation from Tech·Ed 2005: An In-Depth Look at C# 2.0

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>