Difference between Out and Ref keywords[10]

Two important keywords which you used it in your programming, but you  may not understand the difference between them.  lets discuss about the keywords, yes they are “Out” and “ref”

Both these keywords (out and  ref) are used when passing a parameter to a method

What is out?

Out is keyword explicitly tells the compiler that the variable defined is a output variable, so once after the function execution. you will get the result in the “Out” variable.

What is ref?

ref keyword explicitly tells the compiler to pass the variable as “pass by reference” not by “pass by value”. When using ref keyword, we are passing the reference ( address of the variable). Any changes happened to the reference will get affected in  variable.

Difference between “out” and “ref”:  There is no significant difference between them except only one. You need to assign value to “ref” variable before use, you don’t need to do that with out keyword.

A simple demo program to explain the difference between out and ref.

There are three methods:

  • Method 1: Sample – Integer as argument – value is passed by value
  • Method 2: SampleRef – Integer as argument – value is passed by reference – we explicitly tells the compiler to pass the value by reference.
  • Method 3:SampleOut – Integer as argument – value is passed by reference. with keyword as “Out”

Output of the program:

Difference between out and ref

Difference between out and ref

0 comments… add one

Leave a Comment