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"
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the 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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With