Tuesday, January 03, 2006
« A Crash Course on ASP.NET Control Develo... | Main | Insert Rows with a GridView »

I wrote previously about a pattern using the coalescing operator (??) that I use to wrap ViewState:

public string Title
{
   
get { return (string)ViewState["title"] ?? "Default title"; }
   
set { ViewState["title"] = value; }
}

and

public string TitleID
{
    get { return (int?)ViewState["titleID"] ?? -1; }
   
set { ViewState["titleID"] = value; }
}

In the latter case, int is a value type and I thought the only way you could get things to work was to cast the ViewState to a nullable int type (int?), but there is a better solution:

public string TitleID
{
   
get { return (int)(ViewState["titleID"] ?? -1); }
   
set { ViewState["titleID"] = value; }
}

The difference is subtle but ViewState is an object type and you can apply the coalescing operator directly to it. Then cast that result to an int.

-Andrew

kick it on DotNetKicks.com   Tuesday, January 03, 2006 6:21:23 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview