I am using protobuf-net v2 beta r431 for C# .net 4.0 application. In my application I have a Dictionary<int, IMyClass>
which i need to serialize. A class MyClass
implements IMyClass
interface. As per protobuf's documentations I wrote the code as under:
[ProtoContract]
[ProtoInclude(1, typeof(MyClass))]
public interface IMyClass
{
int GetId();
string GetName();
}
[ProtoContract]
[Serializable]
public class MyClass : IMyClass
{
[ProtoMember(1)]
private int m_id = 0;
[ProtoMember(2)]
private string m_name = string.Empty;
public MyClass(int id, string name)
{
m_id = id;
m_name = name;
}
public MyClass()
{
}
#region IMyClass Members
public int GetId()
{
return m_id;
}
public string GetName()
{
return m_name;
}
#endregion
}
However, as per my application's design, the interface is defined at a higher level (in a different project than the classes) and it is not possible to determine the class/classes that implements this interface at compile time. Hence, it gives compile time error for [ProtoInclude(1, typeof(MyClass))]. I tried to use [ProtoInclude(int tag, string KownTypeName)] as following:
[ProtoContract]
[ProtoInclude(1, "MyClass")]
public interface IMyClass
{
int GetId();
string GetName();
}
But, this threw an "Object reference not set to instance of an object" exception at line
Serializer.Serialize(stream, myDict);
where Dictionary myDict = new Dictionary(int, IMyClass)(); Please let me know how to use ProtoInclude in this case so as to serialize interface type inside dictionary / list.