Method Parameters

In C#, arguments can be passed to parameters either by value or by reference.

  • Pass by value means passing a copy of the variable to the method.

  • Pass by reference means passing access to the variable to the method.

Modifiers

in parameter modifier

  • The in keyword causes arguments to be passed by reference.

  • The argument for an in parameter must be definitely assigned. The called method can't reassign that parameter.

int readonlyArgument = 44;
InArgExample(readonlyArgument);
Console.WriteLine(readonlyArgument);     // value is still 44

void InArgExample(in int number)
{
    number = 19;    
    // error: Cannot assign to variable 'in int' because it is a readonly variable
}

ref parameter modifier

  • The ref keyword causes arguments to be passed by reference, not by value.

  • The argument for a ref parameter must be definitely assigned. The called method may reassign that parameter.

void Method(ref int refArgument)
{
    refArgument = refArgument + 44;
}

int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 45

out parameter modifier

  • The out keyword causes arguments to be passed by reference.

  • The argument for an out parameter needn't be definitely assigned. The called method must assign the parameter.

int initializeInMethod;
OutArgExample(out initializeInMethod);
Console.WriteLine(initializeInMethod);     // value is now 44

void OutArgExample(out int number)
{
    number = 44;
}

Parameters declared for a method without in, ref or out, are passed to the called method by value.

Last updated