I have a public static class listing my extension methods:
public static void OrderInts (this List<int> ints)
{
ints= ints.OrderBy(c => c).ToList();
}
public static void AddInt(this List<int> ints)
{
ints.Add(34);
}
public static void AddIntAndOrder(this List<int> ints)
{
ints.Add(34);
ints = ints.OrderBy(c => c).ToList();
}
public static void OrderAndAddInt(this List<int> ints)
{
ints = ints.OrderBy(c => c).ToList();
ints.Add(34);
}
Then if I test them, I notice that:
OrderInts does not modify the list of ints.
AddInt adds an item to the list.
AddIntAndOrder adds an item to the list but does not sort it.
OrderAndAddInt does not modify the list.
Any idea why that strange behavior?
PS: If I use a static Util class:
public static void ReorderInts(List<int> ints)
{
ints = ints.OrderBy(c => c).ToList();
}
public static void ReorderIntsByRef(ref List<int> ints)
{
ints = ints.OrderBy(c => c).ToList();
}
then Util.ReorderInts(myVar) does not change the list but Util.ReorderIntsByRef(ref myVar) does.
It's expected behavior and for good reason. Now you have to know two things:
Source: Microsoft documentation on Method parameters.
What your doing e.g. in
OrderInts()is passing a reference type (List<T>) to a method by value (since that's the default) and then within that method you create a new List i. e. a new reference withToList()and assign it to the method parameterints.When you pass the parameter to the method, a copy of that reference is created therefore within the method you only assign a new reference to that copy, the reference outside of the function remains unchanged and still points to the old list, therefore no change is observable from outside the method.
To make it work you'd have to return the new list and then you can observe the change on the new list.
Theoretically you could also use the following which is passing a reference type by reference:
But in general that wouldn't be a good idea because then this method has side-effects which can make code prone to error and hard to debug if you use it without good reason and all over the place.