Useful Code Snippet: Web Property
Write WebControls much? Well, I do and I have a code snippet that I pretty much can't live without. It is used for creating ViewState backed properties. Here is the basic pattern I use when creating properties for my web controls:
public string Name
{
get
{
object o = ViewState["Name"];
return o == null ? String.Empty : (string)o;
}
set { ViewState["Name"] = value; }
}
Basically, you just want a property (in this case a string named "Name") and you want to store it in ViewState. And when the value is being retrieved, if it is not in ViewState, you want to retrieve some default value. This is a pattern that I repeat over and over in my controls. So I made a code snippet to make it easier.
I use the shortcut 'webprop'
and it expands like this:
To install, you just need to place the .snippet file (link to download below) in your 'My Snippets' folder which in windows vista is located at:
C:\Users\<UserName>\Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets
or if you use Visual Studio 2008:
C:\Users\<UserName>\Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets
I hope this is helpful. It saves me a bunch of time.