Prevent changing the value of an object passed through a method in C#

Within C++, you have the const keyword, that can be used to say to the one which calls the method that the argument which passed through the const parameter won’t be changed within the method. This is merely adding a contract. Sure, the compiler does some checking for you, but still it is possible to change the value of your const parameter. See for example this nice example (obtained from

void f(const int* p1, int* p2)
  int i = *p1;         // Get the (original) value of *p1
  *p2 = 7;             // If p1 == p2, this will also change *p1
  int j = *p1;         // Get the (possibly new) value of *p1
  if (i != j) {
    std::cout << "*p1 changed, but it didn't change via pointer p1!\n";
    assert(p1 == p2);  // This is the only way *p1 could be different
int main()
  int x = 5;
  f(&x, &x);           // This is perfectly legal (and even moral!)
  // ...

In the example above, you can simply change variable x in the main method by parsing it twice to the method f. C# doesn’t have a const keyword for parameters. How could you ensure that your method doesn’t change anything to the parameter? I thought of some solutions that may do the trick:

Solution 1

Just do what your method says it does. If the method changes the parameters, this should also represent in the name of the method. The method should call like GetAddressAndChangePerson if the method retrieves the address of a person and changes it. If it changes stuff it doesn’t need to change, the changes are considered to be side-effects in your code.

Solution 2

Construct the method, provided in the method, in such a way it doesn’t allow changes to the object in the first place. Make setters of properties private. However, this is not always possible, since at other points you want to change the object or you don’t own the interface of the object.

Solution 3

The less neat solution is to make a deep copy of the object you passing through the method if you suspect a method changes the state of your object. However, this is not clean and violates solution 1 in the first place.

Posted in Best practices, C#, C++ by Bruno at August 3rd, 2016.
Tags: ,

Leave a Reply