Sunday, April 17, 2011

Reflective Serializer for C#

Reflection would have been a nice feature to have when I was writing MFC C++ back in the day. Anyways, here's an easy way to auto serialize a class. Just have it derive from this class:


    public class ReflectiveSerializer : ISerializable
    {
        public ReflectiveSerializer()
        {
        }


        protected ReflectiveSerializer(SerializationInfo info, StreamingContext context)
        {           
            Type t = GetType();
            foreach (FieldInfo fi in t.GetFields())
            {
                fi.SetValue(this, info.GetValue(fi.Name, fi.FieldType));
            }
        }


        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {            
            Type t = GetType();
            foreach (FieldInfo fi in t.GetFields())
            {
                object o = fi.GetValue(this);
                info.AddValue(fi.Name, fi.GetValue(this));
            }
        }
    }


And then add this constructor to the class:


        protected MyClass(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }


That class gets called automatically when serializing. The class will then be automatically serialized, provided all of its members can be serialized.