title: Can I serialize an ExpandoObject in .NET 4?
body: <p>I'm trying to use a <code>System.Dynamic.ExpandoObject</code> so I can dynamically create properties at runtime. Later, I need to pass an instance of this object and the mechanism used requires serialization. </p>
  
  <p>Of course, when I attempt to serialize my dynamic object, I get the exception:</p>
  
  <blockquote>
    <p><em>System.Runtime.Serialization.SerializationException was unhandled.</em></p>
    
    <p><em>Type 'System.Dynamic.ExpandoObject' in Assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.</em></p>
  </blockquote>
  
  <p>Can I serialize the ExpandoObject? Is there another approach to creating a dynamic object that is serializable? Perhaps using a <a href="http://blogs.msdn.com/b/csharpfaq/archive/2009/10/19/dynamic-in-c-4-0-creating-wrappers-with-dynamicobject.aspx">DynamicObject</a> wrapper?</p>
  
  <p>I've created a very simple Windows Forms example to duplicate the error:</p>
  
  <pre><code>using System;
  using System.Windows.Forms;
  using System.IO;
  using System.Runtime.Serialization;
  using System.Runtime.Serialization.Formatters.Binary;
  using System.Dynamic;
  
  namespace DynamicTest
  {
      public partial class Form1 : Form
      {
          public Form1()
          {
              InitializeComponent();
          }
  
          private void button1_Click(object sender, EventArgs e)
          {            
              dynamic dynamicContext = new ExpandoObject();
              dynamicContext.Greeting = "Hello";
  
              IFormatter formatter = new BinaryFormatter();
              Stream stream = new FileStream("MyFile.bin", FileMode.Create,
                                             FileAccess.Write, FileShare.None);
              formatter.Serialize(stream, dynamicContext);
              stream.Close();
          }
      }
  }
  </code></pre>