Quantcast
Channel: Way 2 Resources - General
Viewing all articles
Browse latest Browse all 10

Where to Use Ref And Out Parameters in C#

$
0
0

Hi,

 

Both out and ref parameters are very useful to return values in same variables, that you pass as an parameter of a method, these are very useful when the requirement is to return more than one values from method.Both of them are by reference type calling but both are functionally different from each other. Both of them we can use for returning more then one value from any function. If your function need some value from the parameter then you should use it as ref Variable and if the function is just returning any value then use out parameter. In my openion use out parameter if your function doesn't need some additional information from your variable, it will be less costly then ref.

The main difference between both of them is initializtion. You have to initialize ref type parameter before sending it to any method and you can pass any default values to method with it.In out parameter you don't need to initialize the paramater before passing it to method, in method body you should initialize it by new keyword.

The second major difference in both of them is, if you have requirement to pass any parameter which is returned from a method the you can not use an out parameter because


// Example of Out Variable
public class TestOut
{
public static int FunTestOut(out int Val1, out int Val2)
{
Val1 = 1;// Here you have to initialize these parameters.
Val2 = 2;
return 1;
}
public static void Main()
{
int num1, num2; // variable need not be initialized
Console.WriteLine(FunTestOut(out num1, out num2));
Console.WriteLine(num1);
Console.WriteLine(num2);
}
}
In this example values will be set to num1 and num2.

// Example of Ref parameter
public class TestRef
{
public static void FunTestRef(ref int Value )
{
Value += 1;
}
public static void Main()
{
int val; // variable need to be initialized before calling method
val = 3;
FunTestRef(ref val);
Console.WriteLine(val);
}
}
}
In this example the value of val will increase by one.

 

 


Viewing all articles
Browse latest Browse all 10

Trending Articles