C#: CIL supports overloading by return type

C# and most other languages that allow method overloading do not allow overloading by return type. What this means is that methods can be overloading only if they differ by parameters. So the following code will not compile as the methods differ only by return type

 class Employee{  //...}class Program{    static int Func(Employee emp) {        return emp.Id;    }    static string Func(Employee emp) {        return emp.Name;   }}

However, CIL does support overloading methods by return types, even though C#, VB does not . To implement convertion operator overloading C# compiler uses this feature (I know of one usage and I'm sure that there are more :) )

Conversion Operator Overloading and return types

In the following code we are overloading the conversion operator for Employee class so that the class can be easily converted (casted) to string or int.

 class Employee{    public string Name;    public int Id;        public static explicit operator int (Employee emp) {         return emp.Id;    }    public static explicit operator string (Employee emp) {         return string.Format("{0} ({1})", emp.Name, emp.Id);    }}Employee employee = new Employee("Abhinaba Basu", 23567);Console.WriteLine((int )employee); Console.WriteLine((string)employee); 

Inspection of the Employee class in the assembly with ILDasm or reflector reveals that there are two methods in it which are generated by the compiler.

.method public hidebysig specialname static
string op_Explicit(class ConversionOperator.Employee emp) cil managed

.method public hidebysig specialname static
int32 op_Explicit(class ConversionOperator.Employee emp) cil managed

Both these methods are identical other than the return types (one returns a string the other an int). So CIL does support method overloading when the methods differ by return types.