C# Frequently Asked Questions

The C# team posts answers to common questions

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

Published Tuesday, May 11, 2004 9:16 PM by CSharpFAQ

Comments

 

Martin Naughton said:

Hi,

Do you know why/how it works in VB, in that case?

Thanks,
Martin
May 12, 2004 2:06 AM
 

Martin Naughton said:

Hi,

Do you know why/how it works in VB, in that case?

Thanks,
Martin
May 12, 2004 2:07 AM
 

Jon Skeet said:

I don't believe read-only properties *can* be named parameters to attribute declarations in VB.NET. What you *can* do in VB.NET which you can't in C# is have *write*-only properties which can be named parameters to attribute declarations.
May 13, 2004 10:49 AM
 

Paul Vick said:

Yes, Jon's got it right -- Eric seems to have flipped "readable" with "writeable."
May 13, 2004 1:06 PM
 

RebelGeekz said:

December 28, 2004 4:53 AM
Anonymous comments are disabled

© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker