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

前端 未结 4 1580
悲哀的现实
悲哀的现实 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:10

    Passing by value means you are passing the actual reference to the location in memory for that object. So if you have a class, something like:

    CustomObj aObj = New CustomObj();
    aObj.SomeString = "Test";
    someMethod(aObj);
    

    And a method header like so:

    someMethod(CustomObj objIn){
         objIn.SomeString = "Changing by value";
    }
    

    And wrote out to the console:

    Console.WriteLine(aObj.SomeString)
    

    It would produce "Changing by value" instead of "Test" because we have a reference to that object.

    By value, conversely, does not work this way.Keeping with our example above:

    int byValue = 0;
    someMeothd(byValue);
    
    someMethod(int numIn){
       numIn++;
    } 
    
    Console.WriteLine(byValue);
    

    Would produce "0".

提交回复
热议问题