Use Serializable attribute to mark a generic class
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class SampleCollection<T> : List<T> {
private int _intData;
private string _stringData;
public SampleCollection(int intData, string stringData) {
this._intData = intData;
this._stringData = stringData;
}
public int IntVal {
get { return this._intData; }
}
public string StrVal {
get { return this._stringData; }
}
}
public class TypeSafeSerializer {
private TypeSafeSerializer() { }
public static void AddValue<T>(String name, T value, SerializationInfo serInfo) {
serInfo.AddValue(name, value);
}
public static T GetValue<T>(String name, SerializationInfo serInfo) {
T retVal = (T)serInfo.GetValue(name, typeof(T));
return retVal;
}
}
public class MainClass {
public static void Main() {
SampleCollection<string> strList = new SampleCollection<string>(111, "Value1");
strList.Add("Val1");
strList.Add("Val2");
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, strList);
stream.Seek(0, SeekOrigin.Begin);
SampleCollection<string> newList = (SampleCollection<string>)formatter.Deserialize(stream);
Console.Out.WriteLine(newList.IntVal);
Console.Out.WriteLine(newList.StrVal);
foreach (string listValue in newList)
Console.Out.WriteLine(listValue);
}
}