Why Overloaded Method Differing in Out and Ref

Ref and Out Parameters

The parameters ref and out determine how the arguments behave when passed to a method. By default the arguments passed to a method are passed by value but ref and out can be used to pass parameters by reference.

Why cannot we have an overload method differing only as out and ref params?

Let's create a sample application and have an overloaded method as in the following:

  1. class Program  
  2. {  
  3.    static void Main(string[] args)  
  4.    {  
  5.       int i = 0;  
  6.       testmethod(out i);  
  7.       testmethod(ref i);  
  8.    }  
  9.    //Error  
  10.    private static void testmethod(out int i)  
  11.    {  
  12.       i = 0;  
  13.       Console.WriteLine(i);  
  14.    }  
  15.    //Error  
  16.    private static void testmethod(ref int i)  
  17.    {  
  18.       Console.WriteLine(i);  
  19.    }  
  20. }  

When you try to build the application, you will get an error stating "Cannot define overloaded method 'testmethod' because it differs from another method only on ref and out".

We know that this would not be possible but let's take a close look at why its not possible.

Create a SampleApplication with two methods as in the following:

  1. class Program  
  2. {  
  3.    static void Main(string[] args)  
  4.    {  
  5.       int i = 0;  
  6.       methodwithout(out i);  
  7.       methodwithref(ref i);  
  8.    }  
  9.   
  10.    private static void methodwithref(ref int i)  
  11.    {  
  12.       Console.WriteLine(i);  
  13.    }  
  14.   
  15.    private static void methodwithout(out int i)  
  16.    {  
  17.       i = 0;  
  18.       Console.WriteLine(i);  
  19.    }  
  20. }  

Go to the Developer Command Prompt for Visual Studio and type ildasm.exe. Try to open the SampleApplication.exe from the bin/Debug folder. It will look as in the following:



Without getting into the IL Code, we can easily find the reason for why it's not possible to overload a method with the only difference of ref and out params. Yes it's because the IL Code maps to the same instructions (in the preceding example testmethodwithout and testmethodwithref have the same signature). To conclude, we can say "Ref and Out are the same for the CLR, but not for the compiler".


Similar Articles