C#: Custom Serializable Class That Inherits From DataTable

03 April 2008

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



permalink   (currently 0 comments)

Add A Comment

Your Name:
* Please enter the code: Captcha Image
   

* Please enter your message: