Home > Interview Questions > C#.NET > What’s difference between ref and out parameters in C#?

What’s difference between ref and out parameters in C#?

by Thamil   on 04/10/2015   Category: C#.NET   |  Level: Intermediate   |  Views: 535    |  Points: 25     |  Gold 


REF parameter
• REF parameter must be initialized before passing to the specific method
• REF is used to pass an argument as a reference, means that when value of the parameter is changed then it’s getting reflected in the calling method as well.
OUT parameter
• No need to be initialized before passing to the specific method when we use OUT parameter.
• But it must be initialized in the called method before it returns back the calling method.

  class Program
{
//Calling Method
static void Main(string[] args)
{

string Name = "John"; //Must be initialized in the calling method
string FullName; //Initialization is not required in the calling method
GetName(ref Name);
Console.WriteLine(Name);
GetFulNameName(out FullName);
Console.WriteLine(FullName);
Console.ReadKey();
}

//Called Method
public static void GetName(ref string Name)
{
Name="Peter"; //This would reflect in the calling method.
}
//Called Method
public static void GetFulNameName(out string FullName)
{
FullName = "John Peter"; // FullName must be initialize before it returns to calling method
}
}

Output:
Peter
John Peter


« Which types are stored in stack and heap in C#?
» Can multiple catch blocks be executed in a single try statement in c#?
Post Question  |  Question Home

Recent Posts

User Responses


No response found, be the first to review this question.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts