Tiny Trick For ViewState Backed Properties

aspnet 0 comments suggest edit

This might be almost too obvious for many of you, but I thought I’d share it anyways. Back in the day, this was the typical code I would write for a value type property of an ASP.NET Control that was backed by the ViewState.

public bool WillSucceed
{
    get
    {
        if (ViewState["WillSucceed"] == null)
            return false;
        return (bool)ViewState["WillSucceed"];
    }
    set
    {
        ViewState["WillSucceed"] = value;
    }
}

I have seen code that tried to avoid the null check in the getter by initializing the property in the constructor. But since the getters and setters for the ViewState are virtual, this violates the warning against calling virtual methods in the constructor. You also can’t initialize it in the OnInit method because the property might be set declaratively which happens before Init.

With C# 2.0 out, I figured I could use the null coalescing operator to produce cleaner code. Here is what I naively tried.

public bool WillSucceed
{
    get
    {
        return (bool)ViewState["WillSucceed"] ?? false;
    }
    set
    {
        ViewState["WillSucceed"] = value;
    }
}

Well of course that won’t compile. It doesn’t make sense to apply the null coalescing operator on a value type that is not nullable. Now if I had stopped to think about it for a second, I would have realized how simple the fix would be, but I was in a hurry and quickly moved on and dropped the issue. What an eeediot! All I had to do was move the cast outside of the expression.

public bool WillSucceed
{
    get
    {
        return (bool)(ViewState["WillSucceed"] ?? false);
    }
    set
    {
        ViewState["WillSucceed"] = value;
    }
}

I am probably the last one to realize this improvement and everyone reading this is thinking, “well duh!”. But in case there is someone out there even slower than me, here you go!

And if I spend this much time trying to write a property, you gotta wonder how I get anything done. ;)

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.

Comments

avatar

19 responses

  1. Avatar for Jeff Atwood
    Jeff Atwood August 6th, 2006

    Wouldn't (!ViewState["WillSucceed"].IsNullOrEmpty()) work as well? Are we casting a string to a bool?

  2. Avatar for Nick
    Nick August 6th, 2006

    Would this hold true for properties backed by Session?

  3. Avatar for Scott
    Scott August 7th, 2006

    re: the first code sample.
    I always used the trinary operator instead of the much wordier if statement.

  4. Avatar for Haacked
    Haacked August 7th, 2006

    @Jeff: no that wouldn't work. If ViewState["WillSucceed"] was null, then that would throw a NullReferenceException.
    Also, we are storing a bool in ViewState["WillSucceed"] not a string. ViewState is of type StateBag which holds a collection of serializable objects.
    @Nick: Yes, I believe so. Any dictionary type collection of objects really.
    @Scott: Trinay, of course. I hardly ever use it, but have been lately. I always found it confusing to read, but I guess I'm more accustomed to seeing it now.

  5. Avatar for Steven Harman
    Steven Harman August 7th, 2006

    Just an FYI...
    The terms trinary and ternary are apparently interchangeable in this context. I had no idea, which is why I had to look up what a trinary operator was.
    The Wikipedia definition for the ternary operator can be found here.

  6. Avatar for Steven Harman
    Steven Harman August 7th, 2006

    Phil,
    I think you need a small CSS tweak... need to clear:both the H3 element of each comment so that they title wraps correctly following a short comment.

  7. Avatar for Haacked
    Haacked August 7th, 2006

    Thanks Steve. Fixed it.

  8. Avatar for Richard Hubers
    Richard Hubers August 7th, 2006

    Another improvement is that ViewState["WillSucceed"] is now only called once.

  9. Avatar for Scott
    Scott August 7th, 2006

    re: Steve.
    Yeah, I'm old-skool. That's how I roll.

  10. Avatar for Simone
    Simone August 8th, 2006

    Fritz Onion talked about that a while ago: http://pluralsight.com/blog...

  11. Avatar for Haacked
    Haacked August 8th, 2006

    Damn that Fritz! Always beating me to the punch. But hey, I think I'm among the first to talk about its thread safety in my recent post.

  12. Avatar for Simone
    Simone August 8th, 2006

    Yes Phil, I guess you're right :D

  13. Avatar for Lothan
    Lothan August 8th, 2006

    If only this would work within our database access logic so we could translate this ugly farce
    Field = (bool) (row.IsNull("Field") ? false : row["Field"]);
    into something a bit cleaner like this
    Field = (bool) (row["Field"] ?? false);

  14. Avatar for Michal Talaga
    Michal Talaga August 10th, 2006

    Check out my article on Visual Studio Code Snippets. There I have included four snippets you can download. Two of them are designed just to provide a ViewState backened property with the ?? operator.
    http://vaultofthoughts.net/...

  15. Avatar for Chris Martin
    Chris Martin August 18th, 2006

    You almost had it the first time. What's wrong with this?
    public bool? WillSucceed{
    get{
    return (bool?)ViewState["WillSucceed"] ?? false;
    }
    set{
    ViewState["WillSucceed"] = value;
    }
    }

  16. Avatar for Haacked
    Haacked August 18th, 2006

    Nothing is wrong with that. But in my case, I didn't want to use a Nullable Boolean.
    If you really want a try-state boolean, then there's no point in even using the null coalescing operator.
    Otherwise, if you really only want true or false, then you're using a nullable type just to save having to type another pair of parenthesis. Why?

  17. Avatar for Chris Martin
    Chris Martin August 18th, 2006

    LOL. Good point.

  18. Avatar for ligAZ blog
    ligAZ blog September 29th, 2006

    Almost a year ago I blogged about how easy is to create a code snippets in VS.NET 2005. Today I will

  19. Avatar for FireStorm
    FireStorm November 15th, 2006

    Thanks for the interesting information!