开发者

Const methods in C#

In C++, you can define a constant method like so:

int func_that_does_not_modify_this(int arg) const {}

Placing const at the end of the function prevents you from accidentally modifying any of the internal properties, and lets the caller know that this function won't modify the ob开发者_JAVA百科ject.

Is there a concept like this in C#?


No, there's nothing like that in C#. It's been talked about a lot, but it's quite difficult to make const work in such a way that it's verifiable at compile time, can't be cast away like it can in C++, and is still reasonably easy to actually use without everyone having to get it perfectly right when they design their own classes.

Of course, if you design your own types to be immutable (like string) then all instance methods on it are effectively const. This isn't always practical, but it's an important technique to use where appropriate.


Code Contract should provide such a feature in the future. Currently, you can mark a method as [Pure], which means it doesn't have any side-effects (i.e. doesn't modify any of the class members). Unfortunately, the current version of the tools does not enforce this rule, so using that attribute is for documentation purpose only. I'm pretty sure that in future version, it will be enforced via static-analysis (i.e. at compile-time), or at least that's what the documentation hints at.

Related SO questions: Pure functions in C#


No. There's nothing similar in C#.

No const & either.

As Jon points out you can obviously implement a const method, but there's no way beyond documentation to let the caller know that a method is const.


C# 8.0 adds support for C++ style const methods, but only to structs. You can add a readonly modifier to a method deceleration to make any modifications to state within it a compiler warning (which you can define as an error if you wish). A readonly struct method may still call a non-readonly method, but that method will be called on a copy of the struct to prevent any changes to the original data.

For more information:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜