9

This works fine:

    Func<string, string> func1 = s => s + "func";
    ViewState["function"] = func1;

However, this does not:

    Func<string, string> func1 = s => s + "func";
    Func<string, string> func2 = s => func1(s);

    ViewState["function"] = func2;

It throws a runtime serialization exception: Type 'MyProjectName._Default+<>c__DisplayClass3' in Assembly 'MyProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Now, I can work around this this time, but I'd like to understand why this is happening so that if, in the future, I have no choice but to compose functions before serialization, I'll have a solution.

Fishtoaster
  • 1,809
  • 2
  • 20
  • 36
  • 1
    Serializing a Func to the the viewstate? Sorry but that just screams bad design, and I wouldn't recommend it. Can you describe the functionality your trying to implement, maybe someone can suggest a better approach. – Juliet Sep 01 '10 at 18:30

1 Answers1

11

What's happening in the second case is that a closure is involved. The use of func1 inside of func2 creates a closure to captured the shared state between the lambdas expressions. Closures are not serializable. When you try and serialize the func it tries to serialize the target object which is the closure and you get your exception.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    Good answer! I faced the same issue today and was able to nail it down to closures, see my newly posted question http://stackoverflow.com/questions/26887460/do-closures-break-serialization. Do you have any official reference to confirm what you stated here? I have not found any so far on my own... – chiccodoro Nov 12 '14 at 13:18