Difference between ‘ref’ and ‘out’ parameters (ref vs out) – C#

  • Both are treated differently @ runtime but same in the compile time, so can’t be overloaded.
  • Both are passed by references except ‘ref’ requires that the variable to be initialized before passed.

ref:

class Program
 {
 static void M1(out int i)
 {
 i = 1;
 i += 1;
 }

static void Main(string[] args)
 {
 int j; //Not assigned
 M1(out j);
 Console.Write(j);
 Console.Read();
 }
 }
}

The output is : 2

out:

class Program
 {
 static void M1(ref int i)
 {
 i = 1;
 i += 1;
 }

 static void Main(string[] args)
 {
 int j=0; //Assigned
 M1(ref j);
 Console.Write(j);
 Console.Read();
 }
}

The output is same: 2, but we have to assigned the variable before used otherwise we will get an error.

Advertisements

, , , ,

  1. #1 by URL on July 16, 2012 - 6:41 am

    I actually like reading by means of and I feel this site got some genuinely utilitarian stuff on it! . 622382

  2. #2 by timmy on August 3, 2012 - 7:50 pm

    Simple and sweet..thanks for the post

Please leave a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: