Why am I getting these out parameter errors in C#?
out
parameters are for when the function wants to pass a value out of itself. What you want here is ref
, which is when the function expects it to be passed in, but can change it.
For examples of how both are supposed to be used, read http://www.dotnetperls.com/parameter. It's explained in simple terms, and you should be able to get a good understanding of it.
You should note that in your code, you never access the variable after the function call, therefore ref
doesn't actually do anything. Its purpose is to send changes back to the original variable.
ref
means that you are passing a reference to a variable that has been declared and initialized, before calling the method, and that the method can modify the value of that variable.
out
means you are passing a reference to a variable that has been declared but not yet initialized, before calling the method, and that the method must initialize or set it's value before returning.
You're getting an error because a variable sent to a method as an out
parameter does not have to be initialized before the method call. The following is 100% correct code:
class Program
{
static void Main(string[] args)
{
First f = new First();
int x;
f.fun(out x);
}
}
Looks like you're looking for ref
instead of out
here:
class First
{
public void fun(ref int m)
{
m *= 10;
Console.WriteLine("value of m = " + m);
}
}
class Program
{
static void Main(string[] args)
{
First f = new First();
int x = 30;
f.fun(ref x);
}
}