Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const methods in C#

Tags:

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

Is there a concept like this in C#?

like image 206
mpen Avatar asked Sep 26 '10 17:09

mpen


People also ask

What are const methods?

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.

Does C have const functions?

Not in standard C, since there are no classes or objects (as in "class instances, i.e. collections of data with associated functions"), there's nothing for the function to be const "against".

When should methods be const?

A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.

What is const modifier in C?

Const means simply, as you described, that the value is read-only. constant expression, on the other hand, means the value is known compile time and is a compile-time constant. The semantics of const in C are always of the first type.


1 Answers

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.

like image 112
Jon Skeet Avatar answered Oct 04 '22 11:10

Jon Skeet