Home > DeveloperSection > Forums > difference between ref and out keywords
Anupam Mishra

Total Post:135

Points:949
Posted on    February-01-2016 10:36 PM

 C# C#  .NET 
Ratings:


 1 Reply(s)
 220  View(s)
Rate this:
Hi Everyone,
 I want to know what is difference between ref and out keywords.Please can anyone give me a exact situation.
thank you.


Anupam Mishra

Total Post:135

Points:949
Posted on    February-01-2016 11:00 PM


If we want to pass a variable as ref parameter we need to initialize it before we pass it as ref parameter to method. Ref keyword will pass parameter as a reference this means when the value of 
parameter is changed in called method it get reflected in calling method also.

i = 10;
public static void RefTest(ref int val1)
{
val1 += 10;
}
Output : 20
If we want to pass a variable as out parameter we don’t need to initialize it before we pass it as out parameter to method. Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method.

int i,j; // No need to initialize variable
OutTest(out i, out j);
public static int OutTest(out int val1, out int val2)
{
val1 = 5;
val2 = 10;
return 0;
}

Don't want to miss updates? Please click the below button!

Follow MindStick