Geeks With Blogs
Marcin Celej blog

I've been working on ASP.NET project lately. What I found is not-pefect-usage of weakly typed constructs such as ViewState, Session, Cache etc.

For me it's obvious that code that contains something like this: this.ViewState["Age"] repeated many times is not-perfect. I believe, it is natural to wrap access to the ViewState into private property thath is strongly typed and is much cleaner to use in your code. What I advise is the snippet shown below:


private int? Age
    get { return this.ViewState["Age"]; }
    set { this.ViewState["Age"] = value; }


It allows you to access the ViewState 'variable' in strongly-typed way. It will also work even if there is no 'variable' set yet - thanks to 'int?' (Nullable int).
The same snippet works with Session, Cache, etc.


Do not be afraid of private properties and methods. Introduce them not only to reuse the code but also to make it pretier.

Posted on Tuesday, August 7, 2007 7:03 PM | Back to top

Comments on this post: ViewState best practice 1 - wrap access to 'weak variable'

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Marcin Celej | Powered by: