Search code examples
c#.netserializationnonserializedattribute

Why do I need "field:" in my attribute declaration "[field:NonSerialized]"?


I can't find "field" listed as a C# keyword anywhere. Does anyone know the background on this?


Solution

  • The C# compiler usually has no trouble figuring out what part of a declaration the attribute applies to. I can think of three cases where you might use it:

    1. Attributes that apply to the assembly. Very visible in AssemblyInfo.cs
    2. An attribute applied to the return value of a P/Invoke declaration, [return:MarshalAs]
    3. Having the attribute apply to the backing variable of a property or event without accessors. Your case.