How many times have you written something like this?

   1: public string MyStringProperty
   2: {
   3:     get
   4:     {
   5:         object s = ViewState["MyStringProperty"];
   6:         if( s == null )
   7:         {
   8:             s = "MyDefaultValue";
   9:         }
  10:         return (String)s;
  11:     }
  12:     set { ViewState["MyStringProperty"] = value; }
  13: }
  14:  
  15: public bool MyBooleanProperty
  16: {
  17:     get
  18:     {
  19:         object b = ViewState["MyBooleanProperty"];
  20:         if( b == null )
  21:         {
  22:             b = true;
  23:         }
  24:         return (bool)b;
  25:     }
  26:     set { ViewState["MyBooleanProperty"] = value; }
  27: }

Wouldn't this be better?

   1: public string MyStringProperty
   2: {
   3:     get { return ViewState.GetValue( "MyStringProperty", "MyDefaultValue" ); }
   4:     set { ViewState["MyStringProperty"] = value; }
   5: }
   6:  
   7: public bool MyBooleanProperty
   8: {
   9:     get { return ViewState.GetValue( "MyBooleanProperty", true ); }
  10:     set { ViewState["MyBooleanProperty"] = value; }
  11: }

With C# 3.5, all you need is this extension method

   1: internal static class MyExtensions
   2: {
   3:     public static T GetValue<T>( this IDictionary bag, string key, T defaultValue )
   4:     {
   5:         object value = bag[key];
   6:         if( value == null )
   7:         {
   8:             value = defaultValue;
   9:         }
  10:         return (T)value;
  11:     }
  12: }

Cheers

posted on Monday, March 10, 2008 1:44 PM
Filed Under [ .Net ASP.Net C# ]

Comments

Gravatar
# re: ViewState Extension Method
posted by Dana Hanna
on 4/17/2008 12:33 PM
This shows typical over use of extension methods.

Lookup the C# operator "??". It does what you want, no extension method needed.

object s = ViewState["MyStringProperty"] ?? "MyDefaultValue";
Gravatar
# re: ViewState Extension Method
posted by Will Smith
on 4/17/2008 3:56 PM
Not exactly. More like ignorance of the compiler directives/operators.

Plus, I've extended this concept further to accept a delegate that returns the type I want, and optionally updates the dictionary with the new value. Not the typical pattern you would see with viewstate, but I've applied this to HttpRuntime.Cache as well.

Take a look at my More Fun With Extension Methods post.
Gravatar
# re: ViewState Extension Method
posted by Thurein
on 10/4/2008 11:37 AM
I like your extension method. It would be much helpful. If you allow me, I would like to modify in this way:

internal static class MyExtensions
{
public static T GetValue<T>(this IDictionary bag, string key, T defaultValue )
{
object value = bag[key] ?? defaultValue;

return (T)value;
}

Post A Comment
Title:
Name:
Email:
Comment:
Verification: