C# Ref vs Out parameter

In C# language you can pass parameters to function with Ref or Out keywords.
Here is some simple example:

public void someFunction(ref string someText)

public void someFunction(out string someText)

 

Ref

  • parameter needs to be initialized before passing to function call
  • two-way – “in” and “out” – function can access initialized value of ref parameter, and can assign value to that parameter

Out

  • does not need to be initialized
  • only 1 way – “out” – function need to assign value to out parameter

Overloading

Same method cannot be overloaded with ref and out argument. Ref and Out are treated same at compilation time, so this example throws error:

public class SomeClass
{
    //Compiler error
    public void Method(ref string someText) {}
    public void Method(out string someText) {}
}

On the other hand, you can overload simple argument with ref or out parameter. This example will compile successfully:

public class SomeClass
{
    //Compile ok
    public void Method(string someText) {}
    public void Method(out string someText) {}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

I am web developer, tech enthusiast and fitness junkie 🙂

Calendar

October 2024
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
28293031