I created two extension methods for the StateBag type (ViewState) the other day and I find them quite handy so I thought I'd share them. They're for the very common task of accessing the values in the ViewState and are called GetValue and SetValue and makes my life a little easier.
Let's say we have two properties, the first is an integer called "Value" and the second a string called "Text", these would probably be implemented something like this (the differences in the implementations has to do with that the int is a value type and that string is a reference type):
The extension methods I created let's us write this in a more straight forward way and we won't have to consider if the return type is a value type or a reference type.
Note that there's no need to cast the return value, this because the extension methods are generic methods and type inference is used. If the default value would be null you'd have to specify the type of the method like "this.ViewState.GetValue<string>("Text", null);" or "this.ViewState.GetValue("Text", (string)null);".
And here they are, the extension methods in all their glory!