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?


Simple use:

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

Hopefully, it helps.


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;

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; }

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).


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).