title: Serializing anonymous delegates in C#
body: <p>I am trying to determine what issues could be caused by using the following serialization surrogate to enable serialization of anonymous functions/delegate/lambdas. </p>
  
  <pre><code>// see http://msdn.microsoft.com/msdnmag/issues/02/09/net/#S3
  class NonSerializableSurrogate : ISerializationSurrogate
  {
      public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
      {
          foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
              info.AddValue(f.Name, f.GetValue(obj));
      }
  
      public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,
                                  ISurrogateSelector selector)
      {
          foreach (FieldInfo f in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
              f.SetValue(obj, info.GetValue(f.Name, f.FieldType));
          return obj;
      }
  }  
  </code></pre>
  
  <p><strong>Listing 1</strong> <em>adapted from</em> <a href="http://www.agilekiwi.com/dotnet/CountingDemo.cs" rel="noreferrer">Counting Demo</a></p>
  
  <p>The main issue I can think of that might be a problem is that the anonymous class is an internal compiler detail and it's structure is not guaranteed to remain constant between revisions to the .NET Framework. I'm fairly certain this is the case based on my research into the similar problem with iterators.</p>
  
  <h2>Background</h2>
  
  <p>I am investigating the serialization of anonymous functions. I was expecting this not to work, but found it did for some cases. As long as the lambda did *not&amp; force the compiler to generate an anonymous class everything works fine. </p>
  
  <p>A SerializationException is thrown if the compiler requires a generated class to implement the anonymous function. This is because the compiler generated class is not marked as serializable.</p>
  
  <h2>Example</h2>
  
  <pre><code>namespace Example
  {
      [Serializable]
      class Other
      {
          public int Value;
      }
  
      [Serializable]
      class Program
      {
          static void Main(string[] args)
          {
              MemoryStream m = new MemoryStream();
              BinaryFormatter f = new BinaryFormatter();
  
              // Example 1
              Func&lt;int&gt; succeeds = () =&gt; 5;
              f.Serialize(m, succeeds);
  
              // Example 2
              Other o = new Other();
              Func&lt;int&gt; fails = () =&gt; o.Value;
              f.Serialize(m, fails); // throws SerializationException - Type 'Example.Program+&lt;&gt;c__DisplayClass3' in Assembly 'Example, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
          }
      }
  </code></pre>
  
  <p><strong>Listing 2</strong></p>
  
  <p>This is similar to the issue of trying to serialize <em>iterators</em> and I had found the following code in a previous search (see <a href="http://www.agilekiwi.com/dotnet/CountingDemo.cs" rel="noreferrer">countingdemo</a>) Using the code from <strong>Listing 1</strong> and an ISurrogateSelector I was able to successfully serialize and deserialize the second failing example.</p>
  
  <h2>Objective</h2>
  
  <p>I have a system that is exposed via a web service. The system has a complex but small state (many objects, not a lot of properties per object). The state is saved in the ASP.NET Cache, but is also serialized to a BLOB in SQL in case of cache expiration. Some objects need to execute arbitrary "events" upon reaching some condition. Hence they have properties accepting Action/Func objects. Contrived example:</p>
  
  <pre><code>    class Command
      {
          public Command(Action action, Func&lt;bool&gt; condition);
      }
  </code></pre>
  
  <p>Somewhere else</p>
  
  <pre><code>    void DoSomethingWithThing(Thing thing)
      {
          state = Store.GetCurrentState();
  
          Command cmd = new Command(() =&gt; thing.Foo(), () =&gt; thing.IsReady())
          state.Add(cmd);
  
          Store.Save(state);
      }
  </code></pre>