C# – Serializing anonymous types

anonymouscserialization

I'd like to convert anonymous type variable to byte[], how can I do that?

What I tried:

byte[] result;

var my = new
{
    Test = "a1",
    Value = 0
};

BinaryFormatter bf = new BinaryFormatter();

using (MemoryStream ms = new MemoryStream())
{
    bf.Serialize(ms, my); //-- ERROR

    result = ms.ToArray();
}

I've got error:

An exception of type
'System.Runtime.Serialization.SerializationException' occurred in
mscorlib.dll but was not handled in user code

Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
in Assembly 'MyProject, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' is not marked as serializable.Additional
information: Type '<>f__AnonymousType10`2[[System.String, mscorlib,

Can somebody help me? What I'm doing wrong? Or this is not possible to do?

Best Answer

Just create a serializable class

[Serializable]
class myClass
{
    public string Test { get; set; }
    public int Value { get; set; }
}

And you can serialize your object the following way:

byte[] result;
myClass my = new myClass()
{
    Test = "a1",
    Value = 0
};
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
    bf.Serialize(ms, my); //NO MORE ERROR
    result = ms.ToArray();
}

But i'ts not possible to serialize a anonymous type

Related Topic