C#: Custom Serializable Class That Inherits From DataTable

To allow a custom type that inherits from System.Data.DataTable to be serializable,  you must do the following:

  1. Add the serializable attribute to the class.
  2. Include a namespace reference to System.Runtime.Serialization.
  3. Implement the “GetObjectData” method for the ISerializable interface.
  4. Add a constructor that takes parameters for SerializationInfo and StreamingContext (in addition to the normal constructor).

The code below illustrates.

namespace TestProject
{
    [Serializable]
    public class MyCustomDataTable : DataTable, ISerializable
    {
        #region Constructors
        public MyCustomDataTable() : base()
        {
        }

        public MyCustomDataTable(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
        #endregion

        …
        // Additions to datatable etc go here

        …
        #region ISerializable Members
        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
        }
        #endregion
    }
}

Note that my reason for requiring serialization was that webparts require saved properties to be serializable (i.e. properties decorated with attributes such as[WebBrowsable(false),  Personalizable(PersonalizationScope.Shared)]).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>