11

I am reading some code in my new project and found out the ex-developer was using Serializable and DataContract together.

[Serializable]

and

[DataContract(Namespace="Some.Name.Space", IsReference = true)]

I assume WCF will ignore Serializable when there is a DataContract attribute. Is this a correct assumption? If not, what are the benefits to use both at the same time?

tonyjy
  • 1,359
  • 3
  • 12
  • 24

1 Answers1

18

Yes, [Serializable] is ignored if [DataContract] is present. This may be useful to e.g. create a type that will have one serialization projection for WCF, and another projection for .NET Remoting (if it is used alongside WCF for legacy reasons).

UPDATE: I just ran into a situation in my own code where both [DataContract] and [Serializable] were necessary. Suppose you have a class with a bunch of auto-generated properties (e.g. public int Foo {get; set;}) that you want to use both in ASP.NET ViewState and in an ASP.NET Web API JSON endpoint (which uses either the Newtonsoft JSON serializer or the DataContractSerializer). For ViewState to work, you need the class to be [Serializable]. However, this breaks JSON serialization, causing JSON like {"_k_BackingField123":456} instead of {"Foo":456}, because in the [Serializable] model the auto-generated property backing fields get serialized instead of the properties themselves. However, if you also add [DataContract] to the type (and [DataMember] to its properties), both the ViewState and the JSON scenarios work perfectly.

Eugene Osovetsky
  • 6,443
  • 2
  • 38
  • 59