views:

526

answers:

4

I was told that in c# attributes are not allowed on the auto-implemented properties. Is that true? if so why?

EDIT: I got this information from a popular book on LINQ and could not believe it! EDIT: Refer page 34 of LINQ Unleashed by Paul Kimmel where he says "Attributes are not allowed on auto-implemented properties, so roll your own if you need an attribute"

+9  A: 

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.

aku
+1  A: 

Note also that any Automatic property will have the CompilerGeneratedAttribute applied to it as well.

ShuggyCoUk
+4  A: 

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.

Jon Skeet
+1  A: 

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.

Sergey Teplyakov