Const methods 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.

Tags:

C#