Friday, 16 February 2007

Generic Dictionary Wrapper Class Cannot be Restored from ViewState

The .NET 2.0 generic Dictionary class can be serialised to and deserialised from the ViewState of a web application but extending the Dictionary class to derive a named collection grounded in the business domain requires some extra attention. Essentially, the derived class needs to call a specific constructor in the base class when deserialisation occurs and this doesn't happen implicitly (List-based classes seem to work fine without modification). Note: the derived class will serialise happily--deserialisation is the problem).

The System.Collections.Generic.Dictionary class defines a constructor used to restore the Dictionary's internal data during the deserialisation process:

"Initializes a new instance of the Dictionary class with serialized data."

protected Dictionary (
SerializationInfo info,
StreamingContext context
)


Constructors are not inherited in C# so a wrapper class must explicitly define this constructor and pass the data back up the inheritance hierarchy to the base Dictionary class:

[Serializable]
public class CustomCollection : Dictionary
{
protected CustomCollection (
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context

) : base (info, context)
{
// no implementation
}
}

Depending on how you construct your wrapper class, you'll most likely want to define additional constructors as well or the default (empty) constructor at a minimum as it will no longer be injected by the compiler with the deserialisation constructor present.

Without this constructor, I was receiving a corrupted ViewState exception

The state information is invalid for this page and might be corrupted.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

6 comments:

Brian said...

Thank you for this!!! This was the answer I needed. I know it's been almost a year since you posted it, but it was exactly the answer I needed!

Adam said...

Like the guy before me, almost a year but I had the same issues trying to put SerializableDictionary by http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx
into ViewState.

Thanks :)

michhes said...

I'm trying to remember why I wanted to drop a dictionary object into viewstate in the first place. Adding stuff to a page's viewstate means extra data to transport from server to client and back again so dropping in a fully-loaded dictionary might not be a great idea.

Adam said...

This is a situation of supporting an existing implementation unfortunately, reworking it is more time as you most likely can guess. I do agree with you on that one.

Kralizek said...

thank you! you helped me :D

Jener said...

Thank you very much! You helped me with this article.

Post a Comment