tags:

views:

153

answers:

2

Class marked as [DataContract] can't be ISerializable at the same time. OK, so how can I serialize this type of object to a binary stream?

private byte[] GetRoomAsBinary(Room room)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, room);
            return stream.ToArray();
        }

I can't make it work without Room being ISerializable. How can I get a byte array from object some other way?

A: 

That's the principle of binary serialization: only [Serializable] classes can be serialized (although I may have read that this restriction was lifted recently). If you want to take control of the serialization process, implement ISerializable.

If the Room class has non-serializable members, you will need ISerializable, too.

What are the members of Room ?

Timores
as i've written: you can't have a class that is serializable and datacontract at the same time. this throws an exception at runtime
agnieszka
You're right, I misunderstood the question.
Timores
Is it acceptable to have a copy of the Room class, say RoomProxy with the same members, serializable but not involved in a DataContract ?In order to avoid the duplication, one could have a subclass of Room that is not marked as [DataContract]; it could be serialized by implementing ISerializable.
Timores
A: 

The solution is to use DataContractSerializer to serialize the object.

agnieszka