Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not having a [DataMember] attribute vs having the [IgnoreDataMember] attribute

Tags:

c#

wcf

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.

like image 618
David Pilkington Avatar asked Nov 14 '13 11:11

David Pilkington


People also ask

Is DataMember attribute required?

You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member.

What is Datacontract and DataMember?

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.

What is the use of Ignoredatamember in Web API?

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.


1 Answers

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:

  • if it is marked as [DataContract], then only the members marked [DataMember] are considered
  • if it is not marked as [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.

like image 191
Marc Gravell Avatar answered Oct 02 '22 01:10

Marc Gravell