Home > Software engineering >  Why is the defined list sorted after list sort from the another class method?
Why is the defined list sorted after list sort from the another class method?

Time:09-19

I'm confused with this implementation, I have simply written this list sorting code snippet to demonstrate my confusion problem. I have a list called numberList which consists of 4 numbers. And I'm passing

    static void Main(string[] args)
    {
        List<int> numberList = new List<int>() { 10, 4540, 32, 989 };

        SortClass sortClass = new();

        sortClass.Sort(numberList);

        foreach (int number in numberList)
        {
            Console.WriteLine(" "   number);
        }

        Console.ReadLine();
    }

I have another class called SortClass which consists of simple Sort() method to sort the list which taking from the Main() method and also it's adding another two values the list.

public class SortClass
{
    public void Sort(List<int> list)
    {
        list.Sort();
        list.Add(1000000);
        list.Add(2000000);
    }
}

The above code give me following output.

 10
 32
 989
 4540
 1000000
 2000000

Can some one please explain why this output coming? I'm not returning the sorted list to the main method here, but initially defined numberList list has been sorted and another two integers are there which I added from the Sort method. how is this happening?

CodePudding user response:

List<T> is refernce type.

You're passing reference to the object, not the object, to Sort method.

Then this object is modified in Sort method, that's why you see such results.

Some further reading

  • Related