tags:

views:

328

answers:

3

I want to retain a variable between postbacks, so I write an accessor to put it into viewstate. Which one of these is the best way to access it? Or is there a better option?

Option 1:

private int Status
{
    get
    {
     try
     {
      return (int)ViewState[@"__Status"];
     }
     catch
     {
      return 0;
     }
    }
    set
    {
        ViewState[@"__Status"] = value;
    }
}

Option 2:

private int Status
{
    get
    {
        if (ViewState[@"__Status"] is int)
        {
            return (int)ViewState[@"__Status"];
        }
        else
        {
            return 0;
        }
    }
    set
    {
        ViewState[@"__Status"] = value;
    }
}

Thanks

Edit: I'm using C# 2.0

+1  A: 

Well, option 2 won't compile, but I think it's the right direction. ;-) Try not to use an exception for this. Inspect the ViewState variable instead.

Dave Markle
Oops, dumb error. Corrected, thanks.
Nick
+2  A: 

Here's the way that I tend to do it:

private int Status
{
  get { return (ViewState["MYSTATUS"] != null) ? (int)ViewState["MYSTATUS"] : 0; }
  set { ViewState["MYSTATUS"] = value; }
}
Rob
Forgot about this method, I've used it before as well - trying to make my code more consistant.. As the viewstate variable will only be read / changed by this accessor, the explicit cast (if not null) should be fine. Thanks.
Nick
A: 

Not exactly an answer, is it reasonable to assume that null is the same as 0. Why not use int? and the property type, then I think you could do something like this:

public int? MyProperty
{
    get
    {
        return ViewState["status"] as int?;

    }
    set
    {
        ViewState["status"] = value;
    }
}
Ralph Shillington
Depending upon the assumptions that the code is making, you might start seeing errors pop-up if you allow the value returned to be null, or you would have to add additional code to check for null.
Rob