What is the difference between ref and out keyword in C#?
What is the difference between ref and out keyword in C#?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Vinitha TPosted Nov 26, 2021, 3:17 PM
MahaPosted Nov 21, 2015, 5:32 AM
Both are quite different. You can see in the following example.
Even though MethodWithRefParam() is a void method (meaning that nothing is returned to the Main() method), when the program prints the variable for the second time within the Main() method, value has been changed to 888, Because variable (var) is passed by reference, the MethodWithRefParam() method "knows" the address of the variable declared in Main() , and makes its changes directly to the original variable that was declared in the Main() method.
//Reference Parameter
using System;
public class ParameterDemo2
{
public static void Main()
{
int var = 4;
Console.WriteLine("In Main var is {0}", var);
MethodWithRefParam(ref var); //calling method with a reference parameter
Console.WriteLine("In Main var is {0}", var);
Console.ReadKey();
}
public static void MethodWithRefParam(ref int parm)
{
parm = 888;
Console.WriteLine("In MethodWithRefParam, param is {0}", parm);
}
}
/*
In Main var is 4
In MethodWithRefParam, param is 888
In Main var is 888
*/
When you use a reference parameter, the passed variable must have an assigned value.
Using an output parameter is convenient when the passed variable doesn't have a value yet. For example, the program uses InputMethod() to obtain values for two parameters. The parameters get their values from the method, so it makes sense to provide them with no values going in, but to have them retain values coming out.
using System;
public class InputMethodDemo
{
public static void Main()
{
int first, second;
InputMethod(out first, out second); //notice use of out
Console.WriteLine("After InputMethod first is {0} and second is {1}", first, second);
}
//notice use of out
public static void InputMethod(out int one, out int two)
{
string s1, s2;
Console.Write("Enter first integer ");
s1 = Console.ReadLine();
one = Convert.ToInt32(s1);
Console.Write("Enter second integer ");
s2 = Console.ReadLine();
two = Convert.ToInt32(s2);
}
}
/*
Enter first integer 2
Enter second integer 4
After InputMethod first is 2 and second is 4
*/
Upendra Pratap ShahiPosted Nov 21, 2015, 3:05 AM
Ranjit PowarPosted Nov 20, 2015, 10:25 PM
Jignesh TrivediPosted Nov 20, 2015, 10:14 PM