by Jim
Sep 23, 2007 7:57 AM
.NET 2.0 has some new language features, among them the null coalescing operator (jQuery15200027220021543247763_1327460644870), which I stumbled on just a few days ago. I need to keep up with my reading.
This is going to be particularly nice when storing properties in the ViewState in ASP.NET.
protected string WidgetName
{
get { return ViewState["WidgetName"] != null ? (string)ViewState["WidgetName"] : ""; }
set { ViewState["WidgetName"] = value; }
}
becomes:
protected string WidgetName
{
get { return (string)ViewState["WidgetName"] ?? ""; }
set { ViewState["WidgetName"] = value; }
}
For base types like int, things are a little tricky because the comparison must be done with nullable types. We can do this:
protected int WidgetId
{
get { return (int)(ViewState["WidgetId"] ?? (object)0); }
set { ViewState["WidgetId"] = value; }
}
Or we can cast our object to a nullable type; the syntax is a little nicer this way. int? is implicitly cast to the return type of int
protected int WidgetId
{
get { return (int?)ViewState["WidgetId"] ?? 0; }
set { ViewState["WidgetId"] = value; }
}