Does passing Reference Types using ref save memory?

后端 未结 4 485

In C#, the parameters to a method can be either reference types or value types. When passing reference types, a copy of the reference is passed. This way, if inside a method

4条回答
  •  离开以前
    2021-01-04 20:36

    Yes, there is a reason: If you want to reassign the value. There is no difference in value types and reference types in that regards.

    See the following example:

    class A
    {
        public int B {get;set;}
    }
    
    void ReassignA(A a)
    {
      Console.WriteLine(a.B);
      a = new A {B = 2};
      Console.WriteLine(a.B);
    }
    
    // ...
    A a = new A { B = 1 };
    ReassignA(a);
    Console.WriteLine(a.B);
    

    This will output:

    1
    2
    1
    

    Performance however has nothing to do with it. This would be real micro optimization.

提交回复
热议问题