posts - 50, comments - 168, trackbacks - 6

My Links

News



View Marcin Celej's profile on LinkedIn

Archives

Post Categories

ViewState best practice 1 - wrap access to 'weak variable'

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.

Conclusion:

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

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Tuesday, August 07, 2007 7:03 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: