Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading