简体   繁体   中英

C# call by reference “return value” is dispensable?

im confronted with some code and i wondered if there is a need for the return value in this method. the method changes some values of an two-dimensonal double array.

public double[,] startsimplex_werte(double[,]f)
{
    double standardabstand_s = 1.0;

    double[] vektor_e1 = newdouble[2]{1.0,0.0};
    double[] vektor_e2 = newdouble[2]{0.0,1.0};
    f[1,1]=f[0,1]+vektor_e1[0]*standardabstand_s;
    f[1,2]=f[0,2];
    f[2,1]=f[0,1];
    f[2,2]=f[0,2]+vektor_e2[1]*standardabstand_s;

    return f;
}

theres an 2 dimensional array called:

double[,]f = new double[3,3];

so then the method is used on the array:

f = berechne.startsimplex_werte(f);

its not important what the method does in detial. my question is:

is it necessary to return the values of the array by writing "return f " in the method. since arrays are reference types, there is a call by reference. so the method already changes the actual data members of the array. i would have written the same method with no return value (void method) and just call the method without assigning it to the array. imo its just important to transfer the array via parameter. both variantes would do the same, or am I wrong?

I hope somebody can tell me if my suggestion is true.

You're right, you don't need to return the array.

You're modifying its content . If you were creating a whole new instance, then you'd have to either return it or pass the array using the ref / out keywords.

You're right, in this case there's no need to return f as it is always the same as the input.

There are a few reason why this might have been done:

  • It does allow the function to allocate a new array and return that, if necessary
  • It's a more "functional" approach to API design
  • If may be part of an API that uses the convention of taking an array and always returning one, and the author has chosen to follow this convention for consistency.

The problem is, that although it is call by reference, only a copy of that reference is passed to your method and not the original reference.

As long as you are modifing the content of the array both references are still pointing to the same object. But if you assign a new array within the method this change would not affect the object outside of your method.

So in general it is better to use the ref keyword in your method if you want to make sure that the orginial object reflects the changes or to use a return value of that method.

But in this special case you don't need a return value or the keyword ref . But again, better use a return value or ref , depending on what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM