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
BinaryFormatterto serialize its objects, it uses either theDataContractSerializer(by default) or some of its other serializers (XmlSerializer,DataContractJsonSerializer, etc).BinaryFormatterwas 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
netTcpBindingWCF still uses theDataContractSerializer, 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 theBinaryFormatterbut use the more fine-grained control that the [DC]/[DM] attributes give you.