So i have been going through our code base and I have seen some our DTO's have a mix and match of [DataMember]
and [IgnoreDataMember]
attributes.
IN the past, we have been told that if we do not want something in the DTO serialised, simply do not add the [DataMember]
attribute. Then I saw the other attribute and did some digging and it seems that this explicitly states that the property will not be serialised.
Now my question is, which is better? Adding [IgnoreDataMember]
or not adding anything.
I have asked around and it seems that [IgnoreDataMember]
is from the days when everything was serialised and you had to dictate what should be ignored (I believe in .Net 2). Then they changed it to the reverse and you had to explicitly state what SHOULD be serialised. Now it seems that you can do both.
You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member.
A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.
NET Core Web Api. When applied to the member of a type, specifies that the member is not part of a data contract and is not serialized. You can fill the id later on in the controller and still maintain one viewmodel.
I have asked around and it seems that [IgnoreDataMember] is from the days when everything was serialised and you had to dictate what should be ignored (I believe in .Net 2). Then they changed it to the reverse and you had to explicitly state what SHOULD be serialised.
Actually that's not quite true; IIRC it has always been both:
[DataContract]
, then only the members marked [DataMember]
are considered[DataContract]
, then it defaults to everything, but you can subtract members using [IgnoreDataMember]
I usually just omit the [DataMember]
of things that I don't want serialized, but in many ways [IgnoreDataMember]
is more explicit - mainly for the benefit of the maintainer. It says "I am intentionally not serializing this", rather than "maybe I know that this isn't being serialized, but maybe I just forgot to add the attribute".
Either will work.
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