Search code examples
c#pass-by-value

Pass by Value in C#


How can I pass an object of a "MyClass" (C#) by Parameter-by-Value to a method? example:

MyClass obj = new MyClass();
MyClass.DontModify(obj); //Only use it!
Console.Writeline(obj.SomeIntProperty);

...

public static void DontModify(MyClass a)
{
    a.SomeIntProperty+= 100;// Do something more meaningful here
    return;
}

Solution

  • By default object types are passed by value in C#. But when you pass a object reference to a method, modifications in the object are persisted. If you want your object to be inmutable, you need to clone it.

    In oder to do it, implement the ICloneable interface in your class. Here is a mock example of how to use ICloneable:

    public class MyClass : ICloneable
    {
      private int myValue;
    
      public MyClass(int val)
      {
         myValue = val;
      }
    
      public void object Clone()
      {
         return new MyClass(myValue);
      }
    }