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)]).

You May Also Like

About the Author: rnowik

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.