Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

27 July 2012

Is method overloading supported with different return type with same signature in .NET


No, method overloading does not support with different return type in C#/VB.NET. If the signature is same (data type and order of arguments) and return type is different we will get error in C# or VB.In C# dev,we will get the error after building the project but in case VB.NET we will get the error beforing building the project.
Below is the piece of code to understand easily.
     public int add(int a,int b)
        {
            return a+b;
        }

        public string add(int a, int b)
        {
            return (a + b).ToString();
        }

C# Complile Error as “ ‘Class_Name' already defines a member called 'add' with the same parameter types”
Function add(ByRef a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function
    Function add(ByRef a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function
VB.NET Complile  error as 'Public Function add(ByRef a As Integer, b As Integer) As Integer' and 'Public Function add(ByRef a As Integer, b As Integer) As String' cannot overload each other because they differ only by return types.

Method overloading can have same method name with different data type and order of the arguments. It will not support different return type for same signature.

0 Comments:

Post a Comment