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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With