Skip to main content
  1. Posts/

ISNULL in C#

··1 min

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

George Tsiokos
Author
George Tsiokos

Leave a comment

Preview

Comments are reviewed before publishing.