Tiny Trick For ViewState Backed Properties

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. ;)

What others have said

Requesting Gravatar... Jeff Atwood Aug 07, 2006 1:41 AM
# re: Tiny Trick For ViewState Backed Properties
Wouldn't (!ViewState["WillSucceed"].IsNullOrEmpty()) work as well? Are we casting a string to a bool?
Requesting Gravatar... Nick Aug 07, 2006 4:39 AM
# re: Tiny Trick For ViewState Backed Properties
Would this hold true for properties backed by Session?
Requesting Gravatar... Scott Aug 07, 2006 11:22 AM
# re: Tiny Trick For ViewState Backed Properties
re: the first code sample.
I always used the trinary operator instead of the much wordier if statement.
Requesting Gravatar... Haacked Aug 07, 2006 11:47 AM
# re: Tiny Trick For ViewState Backed Properties
@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.
Requesting Gravatar... Steve Harman Aug 07, 2006 12:59 PM
# re: Tiny Trick For ViewState Backed Properties
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.
Requesting Gravatar... Steve Harman Aug 07, 2006 1:03 PM
# re: Tiny Trick For ViewState Backed Properties
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.
Requesting Gravatar... Haacked Aug 07, 2006 2:31 PM
# re: Tiny Trick For ViewState Backed Properties
Thanks Steve. Fixed it.
Requesting Gravatar... Richard Hubers Aug 07, 2006 2:55 PM
# re: Tiny Trick For ViewState Backed Properties
Another improvement is that ViewState["WillSucceed"] is now only called once.
Requesting Gravatar... Scott Aug 07, 2006 4:58 PM
# re: Tiny Trick For ViewState Backed Properties
re: Steve.

Yeah, I'm old-skool. That's how I roll.
Requesting Gravatar... Simone Aug 08, 2006 3:58 PM
# re: Tiny Trick For ViewState Backed Properties
Fritz Onion talked about that a while ago: http://pluralsight.com/blogs/fritz/archive/2005/12/07/17313.aspx
Requesting Gravatar... Haacked Aug 08, 2006 5:21 PM
# re: Tiny Trick For ViewState Backed Properties
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.
Requesting Gravatar... Simone Aug 08, 2006 6:11 PM
# re: Tiny Trick For ViewState Backed Properties
Yes Phil, I guess you're right :D
Requesting Gravatar... Lothan Aug 08, 2006 11:10 PM
# re: Tiny Trick For ViewState Backed Properties
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);
Requesting Gravatar... Michal Talaga Aug 10, 2006 4:56 PM
# re: Tiny Trick For ViewState Backed Properties
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/VisualStudioCodeSnippets.aspx
Requesting Gravatar... Chris Martin Aug 18, 2006 4:06 PM
# re: Tiny Trick For ViewState Backed Properties
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;
}
}
Requesting Gravatar... Haacked Aug 18, 2006 4:45 PM
# re: Tiny Trick For ViewState Backed Properties
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?
Requesting Gravatar... Chris Martin Aug 18, 2006 9:06 PM
# re: Tiny Trick For ViewState Backed Properties
LOL. Good point.
Requesting Gravatar... ligAZ blog Sep 29, 2006 9:19 PM
# Code Snippets Returned
Almost a year ago I blogged about how easy is to create a code snippets in VS.NET 2005. Today I will
Requesting Gravatar... FireStorm Nov 16, 2006 1:10 AM
# re: Tiny Trick For ViewState Backed Properties
Thanks for the interesting information!

What do you have to say?

(will show your gravatar)
Please add 7 and 3 and type the answer here: