开发者

Why is there no const member method in C# and const parameter?

开发者 https://www.devze.com 2023-01-24 17:34 出处:网络
Unlike C++, there aren\'t any const member method开发者_如何学运维 and const parameters in C#. What is the reason?First off, there is no requirement that we provide a reason for not implementing a fea

Unlike C++, there aren't any const member method开发者_如何学运维 and const parameters in C#. What is the reason?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消