Keyword ref and code examples in C#

Reading Time: 1 minute

Keyword ref in C# forces an argument to be passed to the method to be passed by reference. It means that argument must be initialized before it is passed to the method. It also means that any change in the argument that happens in called method has to be assigned at calling side as well. So ref parameter is two sided. Ref parameters are passed both into and out of the method.

Code examples for keyword ref in C# is given if an argument is of the struct type and it is passed as ref to SomeFunction

struct SomeNumber
{

public int i;

}
class Program
{

public static void SomeFunction(ref SomeNumber y)

{

y.i = 7;

Console.Write(y.i + ” “);

}

static void Main(string[] args)

{

SomeNumber x = new SomeNumber();

x.i = 15;

Console.Write(x.i + ” “);

SomeFunction(ref x);

Console.Write(x.i + ” “);

Console.ReadLine();

}

}

Output of the program is 15 7 7
If SomeFunction does not changes parameter (y.i =7) is commented, output is 15 15 15
//y.i = 7;
Ref keyword can be used in static and instance function/subroutine.

External links:

Keyword ref in C# code example on Microsoft
Keyword ref in C# code example on Dotnetperls
Keyword ref in C# code example on Stackoverflow
Keyword ref in C# code example on Stackoverflow

Leave a Reply

Your email address will not be published. Required fields are marked *

*