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 ???
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With