How many times have you written something like this?
public string MyStringProperty
{
get
{
object s = ViewState["MyStringProperty"];
if( s == null )
{
s = "MyDefaultValue";
}

return (String)s;
}

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

public bool MyBooleanProperty
{
get
{
object b = ViewState["MyBooleanProperty"];
if( b == null )
{
b = true;
}

return (bool)b;
}

set { ViewState["MyBooleanProperty"] = value; }
}
Wouldn't this be better?
public string MyStringProperty
{
get { return ViewState.GetValue("MyStringProperty", "MyDefaultValue"); }
set { ViewState["MyStringProperty"] = value; }
}

public bool MyBooleanProperty
{
get { return ViewState.GetValue("MyBooleanProperty", true ); }
set { ViewState["MyBooleanProperty"] = value; }
}
With C# 3.5, all you need is this extension method
internal static class MyExtensions
{
public static T GetValue<T>(this IDictionary bag, string key, T defaultValue )
{
object value = bag[key];
if( value == null )
{
value = defaultValue;
}

return (T)value;
}
Cheers
posted on Monday, March 10, 2008 1:44 PM
Filed Under [ .Net ]

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.
Your Comment




 
Please add 6 and 7 and type the answer here: