I have very simple problem. I made a very simple function for you to demonstrate my problem.
static void Main(string[] args)
{
double[,] mydouble
You are assigning values to the elements of your array parameter, but you have to assign y value to the array itself because its defined as out
:
d = new double[1, 4];
The error message is clear - you need to assign a value to your out parameter inside your method:
public static void mynewMatrix(out double[,] d)
{
d = new double[1, 4];
for (int i = 0; i < 4; i++)
{
d[0,i]=i;
}
}
The assignment you made outside the method has no effect. Just write this:
static void Main(string[] args)
{
double[,] mydouble;
mynewMatrix(out mydouble);
}
In c# there are two very similar keywords, ref
and out
.
Both of them pass values by reference, but the difference is:
When you use ref
the compiler will require you to assign your variable prior to calling the method.
When using out
it will not require this. This means that you will not be able to assume that the parameter has already been populated. You will not be able to read its value inside the method.
To illustrate the problem, just imagine what would happen if someone else wrote this code to call your method:
double[,] myUnassignedDouble;
mynewMatrix(out myUnassignedDouble);
Clearly the variable will never be assigned, which is bad.
This leaves you with three options:
void mynewMatrix(ref double[,] d)
void mynewMatrix(out double[,] d)
void mynewMatrix(double[,] d)
The third option will work because so far you don't seam to need to reassign your variable. Obviously that might change as your code becomes more complicated. I assume you did have your reasons for using out
in the first place?
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