Actually, this has nothing to do with an immutable parameter and is not related to the fact that the parameter is a reference type.
The reason you don't see the change is because you are assigning a new value to the parameter inside the function.
Parameters without the ref or out keywords are always passed by value.
I know that you are raising eyebrows now, but let me explain:
The parameter of the reference type, which is passed without the ref keyword, actually passes its reference by value.
For more information, read this Jon Skeet article .
To demonstrate my claim, I created a small program that you can copy and paste to see for yourself, or just check this script .
using System; using System.Collections.Generic; public class Program { public static void Main() { String StringInput = "Input"; List<int> ListInput = new List<int>(); ListInput.Add(1); ListInput.Add(2); ListInput.Add(3); Console.WriteLine(StringInput); ChangeMyObject(StringInput); Console.WriteLine(StringInput); Console.WriteLine(ListInput.Count.ToString()); ChangeMyObject(ListInput); Console.WriteLine(ListInput.Count.ToString()); ChangeMyObject(ref StringInput); Console.WriteLine(StringInput); ChangeMyObject(ref ListInput); Console.WriteLine(ListInput.Count.ToString()); } static void ChangeMyObject(String input) { input = "Output"; } static void ChangeMyObject(ref String input) { input = "Output"; } static void ChangeMyObject(List<int> input) { input = new List<int>(); } static void ChangeMyObject(ref List<int> input) { input = new List<int>(); } }
The output of this program is as follows:
Input Input 3 3 Output 0
Zohar peled
source share