Click here to Skip to main content
11,706,159 members (49,342 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
hi everyone!Can any one tell me the basic difference the ref and out keywords?
Posted 10-Oct-10 19:24pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

must assign a value:
ref - before call the method
out - inside the method
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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:


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

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
        }
    }

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) {  }
}
  Permalink  
v3
Comments
shanjeev at 11-Oct-10 3:17am
   
Excellent answer
Dalek Dave at 11-Oct-10 3:34am
   
Comprehensive Reply!
Member 4371379 at 11-Oct-10 3:39am
   
Good Job. Keep doing good job
Björn Ranft at 6-Mar-12 7:25am
   
Thanks for that Hints, 5!
Madhu Sasi Nair at 17-Oct-13 8:48am
   
Excellent!!!
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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"

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"

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
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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.

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.

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); 
      } 
   } 
}
  Permalink  
v3
Comments
Nelek at 27-Dec-13 4:10am
   
You are almost 3 years late :P
CHill60 at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

ref is input VS out is output
Or say ref is consumer VS out is producer
Laugh | :laugh:
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 8

I got the solutions from DataHaunting for Difference between ref and out in C# . please read it carefully will help you understand to better .
  Permalink  
Comments
CHill60 at 17-Jun-14 13:21pm
   
If you continue posting links to your own articles in "solutions" to old questions, then your account *could* end up being suspended.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 9

gjhdddkjgljkghkl;;kjsgj sfjaaatghhtgayety aaatyrsthyfdtysdg to your own articles in "solut
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 142
1 Sergey Alexandrovich Kryukov 137
2 ppolymorphe 71
3 Mika Wendelius 70
4 chainerlt 70
0 OriginalGriff 9,050
1 Sergey Alexandrovich Kryukov 8,417
2 CPallini 5,189
3 Maciej Los 4,726
4 Mika Wendelius 3,636


Advertise | Privacy | Mobile
Web02 | 2.8.150819.1 | Last Updated 2 Jul 2014
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100