I'm playing around with C# extensions and am confused about mutate methods.
Below are two code samples that are supposed to change the calling List. The first (shuffle) works but the second (CustomExtension) leaves the List unchanged.
At the end of the CustomExtension call the list parameter looks to be changed, but on returning from the method the List looks untouched.
Why does one work and the other doesn't? What's going on?
This works.
readonly private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n < 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
myList.Shuffle();
(The above was ripped from Randomize a List<T>)
This Doesn't
static void CustomExtension(this IList<int> list)
{
list = new List<int>() { 9, 10, 11 };
}
foo.CustomExtension();