Difference between Ref and Out Keyword in C#.net

Category: C#.NetOOPS Comments: No comments

Introduction

Both the parameters passed by reference, While for the Ref Parameter you need to initialize it before passing to the function and out parameter you do not need to initialize before passing to function.

you need to assign values into these parameter before returning to the function.

Ref (initialize the variable)
int getal = 0;
Fun_RefTest(ref getal);
Out (no need to initialize the variable)
int getal;
Fun_OutTest(out getal);
The out and the ref parameters are used to return values in the same variables, that you pass an an argument of a method. These both parameters are very useful when your method needs to return more than one values.

Ref keyword

Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable “must” be initialized before it is passed into a method.

Ex:

namespace TestRefP
{
using System;
public class myClass
{
public static void RefTest(ref int iVal1 )
{
iVal1 += 2;
}
public static void Main()
{
int i; // variable need to be initialized
i = 3;
RefTest(ref i );
Console.WriteLine(i);
}
}
}

 

Out keyword

out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.

It is useful when we want to return more than one value from the method.

Ex:
public class mathClass
{
public static int TestOut(out int iVal1, out int iVal2)
{
iVal1 = 10;
iVal2 = 20;
return 0;
}
public static void Main()
{
int i, j; // variable need not be initialized
Console.WriteLine(TestOut(out i, out j));
Console.WriteLine(i);
Console.WriteLine(j);
}
}

Note: You must assigned value to out parameter in method body, otherwise the method won’t compiled.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

HTML tags are not allowed.