title: Is there a way to store an anonymous delegate in a viewstate?
body: <p>In a <code>WebControl</code>, i have a property <code>Filters</code> defined like this :</p>
  
  <pre><code>public Dictionary&lt;string, Func&lt;T, bool&gt;&gt; Filters
  {
      get
      {
         Dictionary&lt;string, Func&lt;T, bool&gt;&gt; filters =
                 (Dictionary&lt;string, Func&lt;T, bool&gt;&gt;)ViewState["filters"];
         if (filters == null)
         {
            filters = new Dictionary&lt;string, Func&lt;T, bool&gt;&gt;();
            ViewState["filters"] = filters;
         }
         return filters;
      }
   }
  </code></pre>
  
  <p>This webcontrol is a <code>DataSource</code>, i created this property because i want to have the possiblity to filter data easily, eg: </p>
  
  <pre><code>//in page load    
  DataSource.Filters.Add("userid", u =&gt; u.UserID == 8);
  </code></pre>
  
  <p>It works great, however, if I change code to this :</p>
  
  <pre><code>//in page load    
  int userId = int.Parse(DdlUsers.SelectedValue);
  DataSource.Filters.Add("userid", u =&gt; u.UserID == userId);
  </code></pre>
  
  <p>It doesn't works anymore, I get this error : </p>
  
  <blockquote>
    <p>Type System.Web.UI.Page in Assembly '...' is not marked as
    serializable.</p>
  </blockquote>
  
  <p>What happened :</p>
  
  <ol>
  <li>The serializer inspect the dictionary. It sees it contains a anonymous delegate (lambda here) </li>
  <li>Since the delegate is defined in a class, it tries to serialize the whole class, in this case System.Web.UI.Page </li>
  <li>This class is not marked as Serializable </li>
  <li>It throws an exception because of 3.</li>
  </ol>
  
  <p><strong>Is there any convenient solution to solve this ?</strong> I cannot mark all web pages where i use the datasource as [serializable] for obvious reasons.</p>
  
  <hr>
  
  <p><strong>EDIT 1</strong> : something I don't understand. If I store the <code>Dictionary</code> in the <code>Session</code> object (which use a <code>BinaryFormatter</code> vs <code>LosFormatter</code> for <code>ViewState</code>), it works ! I have no idea how it is possible. Maybe <code>BinaryFormatter</code> can serialize any class, even these who are not <code>[serializable]</code> ?</p>
  
  <hr>
  
  <p><strong>EDIT 2</strong> : smallest code to reproduce the problem :</p>
  
  <pre><code>void test()
  {
      Test test = new Test();
      string param1 = "parametertopass";
      test.MyEvent += () =&gt; Console.WriteLine(param1);
  
      using (MemoryStream ms = new MemoryStream())
      {
         BinaryFormatter bf = new BinaryFormatter();
         bf.Serialize(ms, test); //bang
      }
  }
  
  [Serializable]
  public class Test
  {
     public event Action MyEvent;
  }
  </code></pre>