Sunday, July 3, 2016

Ref and Out parameters in c#


ref out param in c#


REF OUT
REF must be initialized before it passes to method OUT its not necessary, but after method call it should get initialized
Extra performance cost Faster
The called method can read argument at anytime The called method must initialize the parameter before using it
ref parameters are used to get a value and return a change to that value Out parameters are useed whe you just need to get a secondary return value


==================================================================

REF



Class tryref
{
  public void (ref int i, ref int j)
  {
     j = i*j;

  }
 }


Calling program

Class Program
{
static void main (string[] args)
{
tryref tf = new tryref();
int i = 5;
int j = 10;
console.writeline("The value of i and j before the call : "+i","+j);
tf.mul(ref i, ref j);
console.writeline("The value of i and j after the call : "+i","+j);
}

}

=======================================================================

OUT



class tryout
{
public int mul (int a, out int b)
{
b = a*a;
return b;
}

}

Calling Program

Class Program
{
static void Main(string [] args)
{
tryout to = new tryout();
// passing out parameter j and getting returning value
to.mul(5, out j);
console.writeline("The value of  j is :"+j);
}

}

========================================================================

Why we use ref and out parameters in C#.



Lets say  we call some method and value of variable changes in that method. However as per method functioning we only receive whatever returned by method i.e. for e.g. method returns integer we get integer value.
When we want to capture the changed value which happened in "called" method we use ref/out parameter irrespective of what method is returning.

No comments:

Post a Comment