Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 294
Motti Avatar asked May 20 '09 10:05

Motti


People also ask

What is advantage of getter and setter methods?

The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.

What is the point of getters and setters C#?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.


2 Answers

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.

like image 118
Jb Evain Avatar answered Sep 20 '22 11:09

Jb Evain


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.

like image 31
David Schmitt Avatar answered Sep 19 '22 11:09

David Schmitt