Why does ArrayCalledWithOrderBy
not change the original passed array but ArrayCalledWithSort
does?
EDIT: As for the links that suggest duplicate. One link does not even has the OrderBy in it, so it is clearly not a duplicate. The other link is actually asking which is better option between OrderBy and Sort, and not why one is not changing the original array.
public static void ArrayCaller()
{
var arr = new string[] { "pink", "blue", "red", "black", "aqua" };
DisplayArray(arr, "Before method calls");
ArrayCalledWithOrderBy(arr);
DisplayArray(arr, "After method call using orderby");
ArrayCalledWithSort(arr);
DisplayArray(arr, "After method call using sort");
}
public static void ArrayCalledWithOrderBy(string[] arr)
{
// this does not change the original array in the calling method. Why not?
arr = (arr.OrderBy(i => i).ToArray());
DisplayArray(arr, "After orderby inside method");
}
public static void ArrayCalledWithSort(string[] arr)
{
// this changes the original array in the calling method.
// Because it is using the same reference?
// So the above code for orderby does not?
Array.Sort(arr);
DisplayArray(arr, "After sort inside method");
}
public static void DisplayArray(string[] arr, string msg)
{
for (int i=0; i<arr.Length; i++)
{
Console.Write($"{arr[i]} ");
}
Console.WriteLine($" - {msg}");
}
// OUTPUT
//pink blue red black aqua - Before method calls
//aqua black blue pink red - After orderby inside method
//pink blue red black aqua - After method call using orderby
//aqua black blue pink red - After sort inside method
//aqua black blue pink red - After method call using sort