I am using a console app using C# that has a method that calls another method and passes an out parameter
public void method1()
{
int trycount = 0;
....
foreach (var gtin in gtins)
{
method2(gtin, out trycount);
}
if (trycount > 5)
{...}
}
public void method2 (string gtin, out int trycount)
{
//gives me a compilation error if i don't assign
//trycount=0;
......
trycount++;
}
I don't want to override the trycount variable = 0 because after the second time the foreach gets executed in the method1 the trycount has a value. I want to pass the variable back so after the foreach I can check the parameter's value.
I know i can do something like return trycount = method2(gtin, trycount) but I wanted to try doing with an out parameter if possible. thanks
It sounds like you want a ref
parameter instead of an out
parameter. Basically out
is like having an extra return value - it doesn't logically have a value initially (it's not definitely assigned, and has to be definitely assigned before the method exits normally).
That's also why you don't have to have a definitely assigned variable to use it as an argument:
int x;
// x isn't definitely assigned here
MethodWithOut(out x);
// Now it is
Console.WriteLine(x);
Logically, x
doesn't have any value when you call MethodWithOut
, so if the method could use the value, what value would you expect it to get?
Compare this with a ref
parameter, which is effective "in and out" - the variable you use for the argument has to be definitely assigned before the call, the parameter is initially definitely assigned, so you can read from it, and changes made to it within the method are visible to the caller.
For more details on C# parameter passing, see my article on the topic.
(As an aside, I'd strongly recommend that you get in the habit of following .NET naming conventions even in demo code. It reduces the cognitive load of reading it.)
See more on this question at Stackoverflow