Motti
Motti

Reputation: 114765

Why do property setters and getters clash with get_X and set_X methods?

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).

Upvotes: 6

Views: 800

Answers (4)

David Schmitt
David Schmitt

Reputation: 59355

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.

Upvotes: 8

Jb Evain
Jb Evain

Reputation: 17499

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.

Upvotes: 8

SillyMonkey
SillyMonkey

Reputation: 1334

Because they may need to be called from external code.

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351566

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.

Upvotes: 1

Related Questions