Home > Software engineering >  How can I create a method in C# that doesn't care about the location of its parameters?
How can I create a method in C# that doesn't care about the location of its parameters?

Time:11-17

Idk if what I said makes sense, if not, here's an example of what I mean:

I created a method which performs "scalar-matrix" multiplication, aka every element of a 2d array gets multiplied by a scalar (by a decimal). Now, it doesn't matter if you do array * decimal or decimal * array, either way you should get the same answer. So far this is what I have:

public static double[,] ScalarMatrixMult(double[,] A, double n)
{
    for (int i = 0; i < A.GetLength(0); i  )
    {
        for (int j = 0; j < A.GetLength(1); j  )
        {
            A[i, j] = A[i, j] * n ;
        }
    }

    return A;
}

public static double[,] ScalarMatrixMult2(double n, double[,] A)
{
    for (int i = 0; i < A.GetLength(0); i  )
    {
        for (int j = 0; j < A.GetLength(1); j  )
        {
            A[i, j] = A[i, j] * n;
        }
    }

    return A;
}

I have 2 different methods for doing the exact same thing... Because they care about the location of the parameters.

Can I somehow capture that idea of "not caring about the location of parameters" in 1 method? Or maybe I can use one of them inside the other? I really want to avoid having to use 2 different names for essentially the same thing (and copy-pasting code snippets).

CodePudding user response:

I really want to avoid having to use 2 different names for essentially the same thing (and copy-pasting code snippets).

You can overload the method, using the same name, and simply make one version just call the other:

public static double[,] ScalarMatrixMult(double n, double[,] A)
{
    return ScalarMatrixMult(A, n);
}
 
public static double[,] ScalarMatrixMult(double[,] A, double n)
{
    for (int i = 0; i < A.GetLength(0); i  )
    {
        for (int j = 0; j < A.GetLength(1); j  )
        {
            A[i, j] = A[i, j] * n ;
        }
    }

    return A;
}

CodePudding user response:

You can use Named Parameters to achieve this. You will define a single method and the caller can provide the parameters by name so that ordering doesn't matter.

If you don't remember the order of the parameters but know their names, you can send the arguments in any order.

  • Related