Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with BinaryFormatter on class with DataContract?

I have a class

[DataContract]
    public class Car
   {
        public bool pbIsHatchBack;
        string prSt = "royi";

    }

And i want to serialize it with BinaryFormatter:

  BinaryFormatter binFormat = new BinaryFormatter();
        Stream fStream = new FileStream("c:\\CarData.dat", FileMode.Create, FileAccess.Write, FileShare.None);
        binFormat.Serialize(fStream, carObj);
        fStream.Close();

But u get this error

Type 'SerializationTypes+Car' in Assembly 'ConsoleApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

If i remove the [DataContract] and replace it with [Serializable] its ok. but why ?

how WCF does it behind the scene (when tcpBinding ?)?

Why can't i use the DataContract ???

like image 814
Royi Namir Avatar asked Jun 02 '26 03:06

Royi Namir


1 Answers

WCF does not use the BinaryFormatter to serialize its objects, it uses either the DataContractSerializer (by default) or some of its other serializers (XmlSerializer, DataContractJsonSerializer, etc). BinaryFormatter was released before WCF (in .NET Framework 1.0, IIRC) so is not aware of the [DataContract]/[DataMember] attributes (which were released in .NET Framework 3.0, along with WCF.

On netTcpBinding WCF still uses the DataContractSerializer, but instead of using a "normal" XML reader/writer, it uses a binary-aware XML reader/writer, which is how we have the binary encoding in WCF.

The WCF serializers understand the [Serializable] attribute, so you can use it with WCF as well. Or you can also use both attributes, if you want your type to be serializable by the BinaryFormatter but use the more fine-grained control that the [DC]/[DM] attributes give you.

like image 145
carlosfigueira Avatar answered Jun 04 '26 17:06

carlosfigueira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!