Share via


Why must attribute properties be read/write in C#?

Q: Why must attribute properties be read/write in C#?

In the C# language, when you define an attribute class, you can define both constructor arguments and properties. For example:

 class MyAttribute: Attribute
{
    string name;
    int number;
    public MyAttribute(string name) { this.name = name;}
    public int Number
    {
        get {return number;}
        set {number = value; }
    }
    public string Name
    {
        get {return name;}
    }
}
[My("Fred", Number=5)]
class Fred
{
}

When you do this, C# requires that properties (such as Number in this example) be read/write properties, though languages such as VB.NET only require them to be readable.

Why? 

A: Using an attribute in C# is logically equivalent to calling the constructor of the attribute class, and then executing the “property = value” part for each named property. Requiring a writeable property is consistent with this view.

Author: Eric Gunnerson

Comments