I've been learning c# for about three weeks now so please bear with me. I got through some online courses with no problem but I've come upon what I think is a very basic, but very real barrier to my understanding of how to use the code to actually write programs.
int inputOutput = 1;
Console.WriteLine(inputOutput); //Prints 1
static void IncrementTest(int inputInput, out int intputOutput)
{
intputOutput = inputInput++;
}
IncrementTest(inputOutput, out inputOutput);
Console.WriteLine(inputOutput); //Also prints 1?
If using out parameters is not the way forward, what is?
The
outkeyword is for parameters that are used for output only. If you want to use a parameter for input and output then you useref. When a parameter is unadorned, it is considered input-only, e.g.Output:
When a parameter is declared
out, it is considered output-only. This code:will not compile because any existing value for an
outparameter is ignored and it is considered uninitialised at the beginning of the method. You MUST assign a value to anoutparameter before using it and, if you don't use it, before the end of the method.Output:
When a parameter is declared
ref, it is considered input-output, e.g.Output: