Thursday, August 14, 2008

Viewstate and the C# ?? null-coalescing operator

The ?? (null coalescing) operator is a handy way to check whether a value is null, and if so return an alternate value.

I find it particularly useful in combination with viewstate for putting terse properties on user controls with default values.

/// A Property that defaults to false unless set otherwise.
public bool SomeProperty
  get { return ViewState["viewstateKey"] as bool? ?? false; }
  set { ViewState["viewstateKey"] = new bool?(value); }

See Also: Scott Gu - The C# ?? null coalescing operator (and using it with LINQ)

No comments:

Post a Comment