Do auto-implemented properties support attributes?

You can apply attributes to automatic properties without a problem.

Quote from MSDN:

Attributes are permitted on auto-implemented properties but obviously not on the backing fields since those are not accessible from your source code. If you must use an attribute on the backing field of a property, just create a regular property.


The easiest way to prove that's wrong is to just test it:

using System;
using System.ComponentModel;
using System.Reflection;

class Test
{
    [Description("Auto-implemented property")]
    public static string Foo { get; set; }  

    static void Main(string[] args)
    {
        var property = typeof(Test).GetProperty("Foo");
        var attributes = property.GetCustomAttributes
                (typeof(DescriptionAttribute), false);

        foreach (DescriptionAttribute description in attributes)
        {
            Console.WriteLine(description.Description);
        }
    }
}

I suggest you email the author so he can publish it as an erratum. If he meant that you can't apply an attribute to the field, this will give him a chance to explain more carefully.


I think that author meant, that you can't apply custom attributes to private backing field. For example, if you want to mark automatic property as non serialized, you can't do this:

[Serializable]
public class MyClass
{
    [field:NonSerializedAttribute()]
    public int Id
    {
        get;
        private set;
    }
}

This code compiles, but it doesn’t work. You can apply attribute to property itself, but you can't apply it for backing field.