AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Monday 23 November 2015

Difference between ref and out parameters in c#

Both ref and out parameters are used to pass arguments within a method. In this Post, you will learn the differences between these two parameters.

Ref Parameter
Ref parameter need to initialize it before you pass it as ref parameter to method. Ref keyword will pass parameter as a reference . when the value of parameter is changed in called method it get changed in calling method also.
class Program
{
 static void Main()
 {
  int i; // variable need to be initialized
  i = 3;
  Refexample(ref i);
  Console.WriteLine(i);
 }
 public static void Refexample(ref int val1)
 {
  val1 += 15;
 }
}
Out put of above code is : 18 

Out Parameter 
Out Parameter don't need to initialize it before passing 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 method.
class Program
{
 static void Main()
 {
  int i,j; // No need to initialize variable
  Outexample(out i, out j);
  Console.WriteLine(i);
  Console.WriteLine(j);
 }
 public static int Outexample(out int val1, out int val2)
 {
  val1 = 5;
  val2 = 10;
  return 0;
 }
}
Out put of above code is :5 10

0 comments :

Post a Comment

  • Popular Posts
  • Comments