Custom Generic ISerializable : Generic Serialization « Generics « C# / C Sharp






Custom Generic ISerializable

 



using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class CustomClass1<T> : ISerializable {
    private int _intData;
    private string _stringData;
    private T _genericData;

    public CustomClass1() { }

    private CustomClass1(SerializationInfo serInfo, StreamingContext context) {
        _intData = (int)serInfo.GetValue("_intData", typeof(int));
        _stringData = (string)serInfo.GetValue("_stringData", typeof(string));
        _genericData = (T)serInfo.GetValue("_genericData", typeof(T));
    }

    public CustomClass1(int intData, string stringData, T genericType) {
        this._intData = intData;
        this._stringData = stringData;
        this._genericData = genericType;
    }

    public void GetObjectData(SerializationInfo serInfo, StreamingContext context) {
        serInfo.AddValue("_intData", _intData);
        serInfo.AddValue("_stringData", _stringData);
        serInfo.AddValue("_genericData", _genericData, _genericData.GetType());
    }

    public int IntVal {
        get { return this._intData; }
    }

    public string StrVal {
        get { return this._stringData; }
    }

    public T GenericVal {
        get { return this._genericData; }
    }

}

public class MainClass{
    public static void Main(){
        CustomClass1<Double> doubleClass;
        doubleClass = new CustomClass1<Double>(111, "Value1", 939.99);

        MemoryStream stream = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, doubleClass);
        stream.Seek(0, SeekOrigin.Begin);

        CustomClass1<Double> newClass = (CustomClass1<Double>)formatter.Deserialize(stream);
        Console.Out.WriteLine("Int Data Member : {0}", newClass.IntVal);
        Console.Out.WriteLine("String Data Member : {0}", newClass.StrVal);
        Console.Out.WriteLine("Generic Data Member : {0}", newClass.GenericVal);
    
    }

}

 








Related examples in the same category