We are testing interview quizzes and created a demo app. Now, We require your help. Please take this quiz and provide inputs for content improvement. Interview Quiz




Useful ‘ref’ and ‘out’ parameters


ref-out parameter

ref-out parameter

It took me some time to realize the real potential of ref and out keywords, till the time I experience a condition which could only be simplified by implementing ref and out keyword.

Lets start by a simple code example and will evolve while moving forward.

  1. public int CalculateSavings(int principal)
  2. {
  3. int result=0;
  4. //Calculate savings and return result
  5. return result;
  6. }

Here we have a method ‘CalculateSavings’ which takes a input parameter ‘principal’ and returns ‘result’ as output parameter. Now, we got a requirement that this method should also return ‘interest’ but if we see that a method can only return only one output, then how can we achieve it?

We can achieve it by using ref or out keyword. Both are useful in this case, though there is a major difference which we will learn shortly.

Two output parameters ‘result’ and ‘interest’ can be achieved by the following code.

  1. int interest;
  2. public int CalculateSavings(int principal, out int interest)
  3. {
  4. int result=0;
  5. //set interest value;
  6. //Calculate savings and return result
  7. return result;
  8. }

Here, ‘out’ parameter is used to tell the compiler that value of variable ‘interest’ will also be available to the members outside of this method and is not limited to the method. This method only sets the value of out variable. Please note that, if value of ‘out’ variable is left unattended in this method and not set then it will result in compile time error.

We will achieve the same by ‘ref’ keyword.

  1. int interest=0;
  2. public int CalculateSavings(int principal, ref int interest)
  3. {
  4. int result=0;
  5. //set interest value;
  6. //Calculate savings and return result
  7. return result;
  8. }

I assume just declaring and initializing ’interest’ before the method will not satisfy you and you will search for more differences over the internet. I behaved similarly but no help till the time i got the requirement which introduces ‘ref’ to me.

Previously, i have mentioned if value of ‘out’ variable is left unattended in this method and not set then it will result in compile time error. But in case of ‘ref’, no compile time error is thrown whether ‘ref’ variable value is set or not.

Instead of looking for the difference between ‘ref’ and ‘out’ keyword, if 5 min. are dedicated for this exercise then surely one can easily solve any similar requirement.

Navigation: