Search code examples
c#referencereturncall

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.


Solution

  • 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.