Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jignesh TrivediRank #16 · 50.3K reputationPosted Nov 20, 2015, 5:14 PM EST
Ranjit PowarRank #553 · 4.4K reputationPosted Nov 20, 2015, 5:25 PM EST
MahaRank #2,573 · 543 reputationPosted Nov 21, 2015, 12:32 AM EST
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 ShahiRank #329 · 7.5K reputationPosted Nov 20, 2015, 10:05 PM EST
Vinitha TRank #8,005 · 230 reputationPosted Nov 26, 2021, 10:17 AM EST