Const methods in C#

Viewed 36700

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 object.

Is there a concept like this in C#?

4 Answers

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:

Related