List passed by ref - help me explain this behaviour

后端 未结 8 2270
名媛妹妹
名媛妹妹 2020-12-02 05:39

Take a look at the following program:

class Test
{
    List myList = new List();

    public void TestMethod()
    {
        myList.Add         


        
相关标签:
8条回答
  • 2020-12-02 06:30

    There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.

    When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.

    0 讨论(0)
  • 2020-12-02 06:31

    Here is an easy way to understand it

    • Your List is an object created on heap. The variable myList is a reference to that object.

    • In C# you never pass objects, you pass their references by value.

    • When you access the list object via the passed reference in ChangeList (while sorting, for example) the original list is changed.

    • The assignment on the ChangeList method is made to the value of the reference, hence no changes are done to the original list (still on the heap but not referenced on the method variable anymore).

    0 讨论(0)
提交回复
热议问题