How to: prevent serialization of event handlers

Today I hit a snag with Serialization, where-by the class that I was trying to serialize (into ViewState) had event handlers declared in it:

/// <summary>
/// Invoked after validation has completed.
/// </summary>
public event EventHandler ValidationComplete;

The problem was that I was subscribing to the event handler from a page’s code-behind, and I had absolutely no intention of marking the code-behind file as [Serializable]. Hence, I was getting an “Error serializing value” type of exception being thrown.

So, how do you stop this happening? Well, unfortunately, you can’t just slap a [NonSerialized] attribute in front of the event, because that attribute can only be used on fields, and technically an event isn’t a field. But actually, this is both the problem and the solution – you have to use a NonSerialized attribute with the “attribute location (set) to field”:

/// <summary>
/// Invoked after validation has completed.
/// </summary>
[field:NonSerialized] public event EventHandler ValidationComplete;

In all honesty I’ve never seen this type of modifier before, but this is taken straight from the MSDN doco for the attribute. It definitely works, but I’d love to know more about why, so if anyone has a clue, please enlighten me.

Posted in .Net, C# by Gerrod at February 12th, 2007.

3 Responses to “How to: prevent serialization of event handlers”

  1. Tod says:

    Thank you for this post. I had read some other, way more complicated work-arounds. Supposedly the “field” attribute makes the “NonSerialized” attribute apply to the underlying delegate rather than the event itself. Here is an old article reference that talks about it.
    http://msdn.microsoft.com/en-us/magazine/cc163902.aspx

  2. David says:

    Thanks! Good thing this article comes up as one of my first Google results ;)

  3. Rob says:

    Yep, some time after this was published, this just saved my sanity. What’s left of it anyway ;)

    One odd thing, is VS2008 marks this attribute with an underline, claiming it’s “not a valid attribute location for this location”… and… “all attribute blocks will be ignored”.

    I’m guessing it’s not ignoring it though as with this in there my code works, without it it doesn’t!

    How strange.

    R

Leave a Reply