Can same argument method with ref and out be overloaded in C#?

Answer: No, methods with ref and out parameters in C# with same number of arguments can’t be overloaded.

For example, in below class we’ll get compiler error if we try to overload one methods having ref parameter and another having out parameter.

class A
{
    //Can't overload same arguments method with ref and out parameters
    //compiler error:'X' cannot define overloaded methods
    //that differ only on ref and out
    public void X(ref int val)
    {       
    }
    public void X(out int val)
    {
        val = 5;
    }   
}

However,it can be overloaded if we have method with ref or out parameter with another method without ref or out parameter in C#.

class A
{  
    //can be overload
    public void X(ref int val)
    {       
    }
    //method without ref or out
    public void X( int val)
    {
        val = 5;
    }   
}

Related Posts