views:

186

answers:

4

In .NET properties are supposed to be first class citizens however in the IL code property getters and setters are implemented as get_PropertyName and set_PropertyName.

class Property
{
    int Value { get { return 42; } }
    int get_Value() { return 6 * 9; }
    void set_Value(int i) { } // Error even though Value is a read only property
}

Output:

error CS0082: Type 'SO.Property' already reserves a member called 'get_Value' with the same parameter types

error CS0082: Type 'SO.Property' already reserves a member called 'set_Value' with the same parameter types

Why did the designers of .NET decide to use a name that may clash with user code? They could have used an illegal character (as Java uses $ for inner class stuff).

+1  A: 

Good question - most of the compiler-generated members (anonymous types and methods) use names that are guaranteed to not clash with any members in your class. I think this particular instance (as well as the generated names for event methods) is a case where Microsoft made a little bit of a mistake.

The only reason I can think of that would justify the decision is that Microsoft may have been hoping to allow other languages to call these methods that do not themselves have a "property" concept or syntax.

Andrew Hare
not so much a mistake, it was deliberate. This indeed makes it easier for languages that do not support the notion of properties to call them, it also makes it easy to get the gettor or settor by reflection.
Abel
+2  A: 

Because they may need to be called from external code.

SillyMonkey
External to the CLR???
Motti
No, "external" to C# - see Jb Evains answer
m0rb
+6  A: 

For languages that don't have the concept of properties, such as J# (which may very well have influenced that design decision), it's still necessary to have a simple name to call them.

Jb Evain
+6  A: 

The Common Language Specification (CLS) requires the use of get_ and set_ methods in the IL (decorated with special bits) when implementing Properties. This is necessary so that different compilers (C#, managed C++, VB.NET, J#, IronPython, etc.) create interoperable bytecodes.

Thus underscores are not "legal" characters in the broader sense. They are not CLS-compliant and therefore should not be used in non-private interfaces.

Also, see this article about writing CLS-compliant code on the MSDN.

David Schmitt