Ref and out parameters are used to pass an argument within a method.
Ref and out will change the behavior of function parameters. Sometimes we want the actual value of a variable to be copied as the parameter. Other times we want a reference. These modifiers affect definite assignment analysis.
The compiler demands that an out parameter be "definitely assigned" before exit from the method. There is no such restriction with the ref type.
Ref Parameter
The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.
public static int square(ref int num)
{
int result = num * num;
num++;
return result;
}
static void Main(string[] args)
{
int n = 10;
Console.WriteLine("square of n value:" + square(ref n));
Console.WriteLine("Current value of n: {0}", n);
}
Out Parameter
The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method. Usually out keyword is used when user want to return more than one value from the method.
public static void complexMath(int num, out int sqr, out int cube)
{
sqr = num * num;
cube = num * num * num;
return;
}
static void Main(string[] args)
{
int n = 10;
int sqr, cube;
complexMath(n, out sqr, out cube);
Console.WriteLine("square of n value:{0}", sqr);
Console.WriteLine("Cube of n value:{0}", cube);
}
Optional Parameters
A method with an optional parameter can be called with only some of its parameters specified. Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.
using System;
class Program
{
static void Main()
{
printDetails (“Satish”, 23); // prints name : Satish, age : 23
// You can omit the age parameter, then age will be 25
printDetails (“Satish”); // prints name : Satish, age : 25
}
static void printDetails(string name, int age = 25)
{
Console.WriteLine("name = {0}, age = {1}", name, age);
}
}
Happy learning.
To know more about Out parameter, follow below articles