Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
4.11/5 (8 votes)
See more:
hi everyone!Can any one tell me the basic difference the ref and out keywords?
Posted

must assign a value:
ref - before call the method
out - inside the method
 
Share this answer
 
The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. For example:


C#
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}


C#
class RefExample
    {
        static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }
        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);
            // Output: 45
        }
    }


MIDL
Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile.

class CS0663_Example
{
    // compiler error CS0663: "cannot define overloaded
    // methods that differ only on ref and out"
    public void SampleMethod(out int i) {  }
    public void SampleMethod(ref int i) {  }
}

Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:

class RefOutOverloadExample
{
    public void SampleMethod(int i) {  }
    public void SampleMethod(out int i) {  }
}
 
Share this answer
 
v3
Comments
shanjeev 11-Oct-10 3:17am    
Excellent answer
Dalek Dave 11-Oct-10 3:34am    
Comprehensive Reply!
Member 4371379 11-Oct-10 3:39am    
Good Job. Keep doing good job
El_Codero 6-Mar-12 7:25am    
Thanks for that Hints, 5!
Madhu Nair 17-Oct-13 8:48am    
Excellent!!!
The keyword out is used to get the value from the function.

1. You don't need to initialize the value in the calling function.
2. Need to initialize the value in the called function, otherwise the compiler will report an error.

void funcA(out int a)
{
  a = 0; // at-least one statement should be there that
         // defines the value for the out parameter
         // otherwise compiler will report an error
  ...
}

void funcB() // calling function
{
  ...
  int a;
  funcA(out a); // note: value of a is not initialized.
  ...
}



The keyword ref is to pass and get modified value from a function.

1. You need to initialize the variable before you call the function.
2. Function may or may not change the value of the ref parameter (if it doesn't change any thing then whats the purpose?)

void funcA(ref int a)
{
  ...
  a = a + 1; //modifying the value
  ...
}

void funcB() // calling function
{
  ...
  int a = 1;
  funcA(ref a); // note: value of a is not initialized.
  // now a = 2
  ...
}


Overriding of methods with only difference keyword, as shown below, will lead to compile time error "cannot define overloaded methods that differ only on ref and out"

C#
static public void funcA(out int a)
{
  a = 1;
}

static public void funcA(ref int a)
{
  a = a + 1;
}



We can assign a value to the out parameter function in the caller function. However, this will lead to compile time exception "Use of unassigned out parameter a"

C#
namespace ConsoleApplication1
{
    class Program
    {
        static public void funcA(out int a)
        {
            if (a == 1)
                a = 2;
            else a = 1;
        }
        static void Main(string[] args)
        {
            int a = 1;
            funcA(out a);
        }
    }
}


HTH
 
Share this answer
 
Generally we can return only one value of from a method.
Out and Ref are used when we are in need to return multiple values from a method. Out and Ref both returns values in the same varialbe that we pass in mathod arguments.

OUT
Any changes made to the parameter will be reflected in the variable.

C#
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);
   }
}


Ref

If you do any changes to the variable, they will be reflected in the variable.

You can even use ref for more than one method parameters.

C#
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); 
      } 
   } 
}
 
Share this answer
 
v3
Comments
Nelek 27-Dec-13 4:10am    
You are almost 3 years late :P
CHill60 27-Dec-13 13:35pm    
Reason for my downvote. 3 years late. Question already adequately answered. This solution does not explain the differences. Oh and this is not a blog by the way
ref is input VS out is output
Or say ref is consumer VS out is producer
:laugh:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900