Unlike C++, there aren't any const member method and const parameters in C#. What is the reason?
To make a member function constant, the keyword “const” is appended to the function prototype and also to the function definition header. Like member functions and member function arguments, the objects of a class can also be declared as const.
A 'const member function' is not allowed to modify the object it is called on, but static member functions are not called on any object. It is used directly by scope resolution operator. Thus having a const static member function makes no sense, hence it is illegal.
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
The const means that the method promises not to alter any members of the class. You'd be able to execute the object's members that are so marked, even if the object itself were marked const : const foobar fb; fb.
First off, there is no requirement that we provide a reason for not implementing a feature. Features are extremely expensive; there has to be a justification for implementing a feature, not a justification for not implementing a feature.
Second, C# is not a clone of C++ or C. Just because a feature is in some other language is not a reason to put it in C#.
Third, "const" is deeply, tragically broken in C and C++. "const" gives you no guarantee that you can actually rely upon. If you are the caller of a method that takes a const reference then you have no guarantee whatsoever that the method honours the constness; the method has many ways of mutating a const reference. If you are the consumer of a const reference then you have no guarantee that the underlying object actually will not mutate arbitrarily. Since the contract is not enforced on either the caller or the callee side, it is far weaker than any other guarantee that we would like to make in the type system. We would not want to replicate such a broken system.
Fourth, putting constness in the CLR type system means that every language would have to use the same implementation of constness; since different languages have different meanings for constness, that would be making it harder to bring more languages to the CLR, not easier.
There are many reasons for not doing this extremely expensive feature, and very few reasons to do it. Expensive, unjustified features don't get implemented.
C# doesn't have it because .NET doesn't. .NET doesn't because the CLR development team decided it wasn't worth the effort.
You can read on MS blogs like Raymond Chen's "The Old New Thing" or Eric Lippert's "Fabulous Adventures in Coding", how Microsoft prioritizes features.
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