Hi Friends
I know out and ref are used to return more than one value from function but I want to know what is the differenece between them ? Please explain with an example ?
Thanks
Loading
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.
Posted Feb 2, 2012, 6:39 PM
Ref parameter
Variable values are given in the Main() method but can be altered by a method call.
Out parameter
Variable values are not given in the Main() method but can be obtained by a method call.
The way I understood. But I am not an adept in C# therefore my explanation is questionable.
//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);
}
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 //Note that var value has been changed after method call
*/
//Out parameter
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
*/
/*
Note that values for var are not given in the Main() method but obtained by a method call
*/