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

Published 11 May 04 09:16 PM

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

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Martin Naughton said on May 12, 2004 2:06 AM:
Hi,

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

Thanks,
Martin
# Martin Naughton said on May 12, 2004 2:07 AM:
Hi,

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

Thanks,
Martin
# Jon Skeet said on May 13, 2004 10:49 AM:
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.
# Paul Vick said on May 13, 2004 1:06 PM:
Yes, Jon's got it right -- Eric seems to have flipped "readable" with "writeable."
# RebelGeekz said on December 28, 2004 4:53 AM:
[http://itpeixun.51.net/][http://aissl.51.net/][http://kukuxz003.freewebpage.org/][http://kukuxz001.51.net/][http://kukuxz003.51.net/][http://kukuxz005.51.net/][http://kukuxz002.51.net/][http://kukuxz004.freewebpage.org/][http://kukuxz007.51.net/][http://kukuxz001.freewebpage.org/][http://kukuxz006.51.net/][http://kukuxz002.freewebpage.org/][http://kukuxz004.51.net/][http://kukuxz008.51.net/][http://kukuxz009.51.net/][http://kukuxz005.freewebpage.org/][http://kukuxz006.freewebpage.org/][http://kukuxz007.freewebpage.org/][http://kukuxz009.freewebpage.org/]

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker