can somebody explain me what does “passing by value” and “Passing by reference” mean in C#?

前端 未结 4 1582
悲哀的现实
悲哀的现实 2021-01-20 00:50

I am not quiet sure about the concept of \"passing by value\" and \"passing by reference\" in c#. I think Passing by value mean :

    int i = 9;
4条回答
  •  遥遥无期
    2021-01-20 01:14

    This is a very extensive subject so I will only try to answer your direct question. Passing something by value or reference to a method, will depend on what you're actually sending.

    If it's a value type it will be sent by value, if it's a reference type it will send the reference by value. Basically it will send the variable itself to the method.

    If you want true referencing, you have to use the ref keyword.

    An example to showcase it:

    void Main()
    {
        int x = 5;
        Console.WriteLine (x);
        Test(x);
        Console.WriteLine (x);
    
        MyClass c = new MyClass();
        c.Name = "Jay";
        Console.WriteLine (c.Name);
        TestClass(c);
        Console.WriteLine (c.Name);
    }
    
    private void Test(int a){
     a += 5;
    }
    
    private void TestClass(MyClass c){
     c.Name = "Jeroen";
    }
    
    public class MyClass {
     public String Name {get; set; }
    }
    

    Output:

    5
    5
    Jay
    Jeroen

    An int is a value type and thus its value is sent to the method. This means that any adjustment on that parameter will only be done on the local copy inside the method.

    However, a class is a reference type and thus myClass will send its memory location. This means that by changing the data inside the given object, this will also change the value of this class in different scopes because they both refer to the same memory location.

    If you'd use the ref keyword, the reference would be transmitted.

    If you want more information, take it from a much more experienced person than me.

提交回复
热议问题