Updated on Kisan Patel
The ref
and our
keyword can be used to change the behavior of the method parameters. When we pass a variable to the method, the runtime generated a copy and passes that copy to the method.
For Example,
using System; namespace ConsoleApp { class Tester { public static void Main(string[] args) { int a = 3; Square(a); Console.WriteLine("The value of a is " + a); } public static int Square(int i) { return i = i * i; } } }
Here, you can see we have create one method named “Square”. When we call method Square() in Main() method and pass a variable a then a copy of the variable a is passed to the Square method and not the variable a. Also, note that i is the local variable in Square() and a is the local variable in Main(). Hence, variables can be accessed within their containing methods only.
C# provides a keyword, ref, which means argument to be passed by reference, not by value. So the effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method.
To use a ref parameter, Both the method signature and calling method should be declared as ref keyword.
C# ref Keyword Example
using System; namespace ConsoleApp { class Tester { public static void Main(string[] args) { int a = 9; Square( ref a ); Console.WriteLine("The value of a is " + a); } public static int Square( ref int i ) { return i = i * i; } } }
Here is the output of the above C# program…
C# out and ref, both keyword indicate that the parameter is being passed by reference. However, when using the out keyword, is not necessary to initialize the variable.
C# out Keyword Example
using System; namespace ConsoleApp { class Tester { public static void Main(string[] args) { int a; Square( out a ); Console.WriteLine("The value of a is " + a); } public static int Square( out int i ) { return i = 4 * 4; } } }
The output of the above C# program…