Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do auto-implemented properties support attributes?

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"

like image 232
suhair Avatar asked Jan 21 '09 11:01

suhair


People also ask

What is true about auto-implemented properties?

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property.

Which statements apply to auto-implemented property?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What are auto properties?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it. Instead of writing property like this: public class Dummy.

What is properties in C# with example?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.


2 Answers

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.

like image 50
aku Avatar answered Oct 14 '22 18:10

aku


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.

like image 30
Jon Skeet Avatar answered Oct 14 '22 17:10

Jon Skeet