Correct way of storing c# property in ViewState

It's very useful to store control or page properties in ViewState. For example, you have ArticleId which comes from QueryString. You need to verify QueryString parameters format, make sure that this not a hack attemp. If it is in correct format, then make sure that article exists in database and etc. After postback you need to do this all over again. However you can store verified ArticleId in ViewState, so after postback you don't need to do verification all over again.

I used to store c# property in ViewState as follow:

public int AritcleId


    get { return ViewState["AritcleId"] != null ? (int)ViewState["AritcleId"] : 0; }

    set { ViewState["AritcleId"] = value; }



I even created a snippet for this. I knew about ?? c# operator, but never really used it. However ViewState property is a classic example for null-coalescing operator. Code above can be rewritten like this:

public int AritcleId


    get { return (int)(ViewState["AritcleId"] ?? 0); }

    set { ViewState["AritcleId"] = value; }



And here is a code snippet:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="">

  <CodeSnippet Format="1.0.0">


















        <Literal Editable="true">


          <ToolTip>Property Name</ToolTip>





        <Literal Editable="true">







        <Literal Editable="true">








      <Code Language="csharp"><![CDATA[public $int$ $MyProperty$


    get { return ($int$)(ViewState["$MyProperty$"] ?? $DefaultValue$); }

    set { ViewState["$MyProperty$"] = value; }







You can create, change and manage code snippets using Snippet Designer. Don't forget to encrypt your ViewState as described in Encrypt ViewState in ASP.NET MSDN article.

kick it on

Posted on Sunday, December 14, 2008 by | Comments (2) | Add Comment



Re:Correct way of storing c# property in ViewState


Great !

Using the null-coalescing operator trick is awesome.

There are plenty of articles that manually check for null
by using 'if statements:

But your method is the best!


Posted on 2/10/2009 3:20:42 AM by Charles Rex #

Re: Correct way of storing c# property in ViewState

Hello there,
This was awesome learning for me. I would want you to emphasize on what goes in the ViewState property though. Newbies like me will be lost as in what goes inside. Though it is obvious enough from the code that the property name as a string should be going in with a type case but still many beginners will make that mistake.
Thank you for this post.

Posted on 10/28/2014 11:09:24 PM by Akshay Halasangi #

New Comment

Your Name:
Email (for internal use only):
Code above:


Valid HTML5