Tuesday, December 09, 2008

Null coalescing operator in C# 2.0 for ASP.NET ViewState property access

instead of

public bool Enabled
{
get
{
if(ViewState["Enabled"] == null)
return false;

return (bool)ViewState["Enabled"];
}
}

we can now write:

public bool Enabled
{
get
{
return (bool)(ViewState["Enabled"] ?? false);
}
}

Cool! But if we are dealing with a complex type i prefer defensive casting, using something like:

public ComplexObject Complex
{
get
{
return ViewState["Complex"] as ComplexObject;
}
}

No comments: