NonSerialized on property

C#.NetSerializationProperties

C# Problem Overview


When I write code like this

[XmlIgnore]
[NonSerialized]
public List<string> paramFiles { get; set; }

I get the following error:

Attribute 'NonSerialized' is not valid on this declaration type.
It is only valid on 'field' declarations.


If I write

[field: NonSerialized]

I get the following warning

'field' is not a valid attribute location for this declaration.
Valid attribute locations for this declaration are 'property'.
All attributes in this block will be ignored.


If I write

[property: NonSerialized]

I get the following error (again):

Attribute 'NonSerialized' is not valid on this declaration type.
It is only valid on 'field' declarations.


How can I use [NonSerialized] on a property?

C# Solutions


Solution 1 - C#

Simple use:

[XmlIgnore]
[ScriptIgnore]
public List<string> paramFiles { get; set; }

Hopefully, it helps.

Solution 2 - C#

Well... the first error says that you can't do that... from http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx

 [AttributeUsageAttribute(AttributeTargets.Field, Inherited = false)]
 [ComVisibleAttribute(true)]
 public sealed class NonSerializedAttribute : Attribute

I suggest using backing field

 public List<string> paramFiles { get { return list;}  set { list = value; } }
 [NonSerialized]
 private List<string> list;

Solution 3 - C#

From C# 7.3 you may attach attributes to the backing field of auto-implemented properties.

Hence the following should work if you update your project's language to C# 7.3:

[field: NonSerialized]
public List<string> paramFiles { get; set; }

Solution 4 - C#

For those using JSON instead of XML you can use the [JsonIgnore] attribute on properties:

[JsonIgnore]
public List<string> paramFiles { get; set; }

Available in both Newtonsoft.Json and System.Text.Json (.NET Core 3.0).

Solution 5 - C#

As of .NET 3.0, you can use DataContract instead of Serializable. With the DataContract though, you will need to either "opt-in" by marking the serializable fields with the DataMember attribute; or "opt-out" using the IgnoreDataMember.

The main difference between opt-in vs opt-out is that opt-out by default will only serialize public members, while opt-in will only serialize the marked members (regardless of protection level).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIAdapterView Question on Stackoverflow
Solution 1 - C#Anton NorkoView Answer on Stackoverflow
Solution 2 - C#wieroView Answer on Stackoverflow
Solution 3 - C#BfedView Answer on Stackoverflow
Solution 4 - C#Ziad AkikiView Answer on Stackoverflow
Solution 5 - C#TezraView Answer on Stackoverflow