Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Composed Func?

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.

like image 392
Fishtoaster Avatar asked Sep 01 '10 18:09

Fishtoaster


People also ask

Can functions be serialized in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .

How many types of serialization are there in C#?

There are three types of serialization in . Net : Binary Serialization, SOAP Serialization and XML Serialization. Binary serialization is the process where you convert your . NET objects into byte stream.

What is serializing and Deserializing?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

Can functions be serialized?

Capturing modules in a JavaScript function Because a module is just a normal JavaScript value, it is possible to serialize it just like any other value.


1 Answers

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.

like image 59
JaredPar Avatar answered Oct 07 '22 23:10

JaredPar