Use of unassigned out parameter, c#

If the array is defined OUTSIDE of the function, you should use a ref (or nothing, considering the array is a reference type). out means the parameter will be initialized in the function before it returns. Some examples of use:

static void Main(string[] args)
{
    double[,] mydouble;
    mynewMatrix(out mydouble);// call of method

    double[,] mydouble2 = new double[1, 4];
    mynewMatrix2(mydouble2);// call of method

    // useless for what you want to do
    mynewMatrix3(ref mydouble2);// call of method
}

public static void mynewMatrix(out double[,] d)
{
    d = new double[1, 4];

    for (int i = 0; i < 4; i++)
    {
        d[0, i] = i;
    }
}

public static void mynewMatrix2(double[,] d)
{
    for (int i = 0; i < 4; i++)
    {
        d[0, i] = i;
    }
}

// useless for what you want to do
public static void mynewMatrix3(ref double[,] d)
{
    for (int i = 0; i < 4; i++)
    {
        d[0, i] = i;
    }
}

I’ll add that if you don’t know what is the difference between ref and out you could read Difference between ref and out parameters in .NET

Leave a Comment