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
- Anonymous
May 11, 2004
Hi,
Do you know why/how it works in VB, in that case?
Thanks,
Martin - Anonymous
May 11, 2004
Hi,
Do you know why/how it works in VB, in that case?
Thanks,
Martin - Anonymous
May 13, 2004
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. - Anonymous
May 13, 2004
Yes, Jon's got it right -- Eric seems to have flipped "readable" with "writeable." - Anonymous
December 27, 2004
[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/]