I have the following code and it runs successfully. But carefully note its output:
using System;
class Base
{
public int f(int i)
{
Console.Write("f (int): ");
return i + 3;
}
}
class Derived : Base
{
public double f(double i)
{
Console.Write("f (double) : ");
return i+3.3;
}
}
class MyProgram
{
static void Main(string[] args)
{
Derived obj = new Derived();
Console.WriteLine(obj.f(3));
Console.WriteLine(obj.f(3.3));
Console.ReadKey(); // write this line if you use visual studio
}
}
Output: f(double) : 6.3 f(double): 6.6 Expected Output: f(int) : 6 f(double) : 6.6
Here it calls only Derived class method. But if I will change this program a little bit like shown below then output is unexpected. Then I tried something and I think it is to the order of precedence for types. When I swapped the Base class from int to double and Derived class from double to int, then the expected output was true.
using System;
namespace MyProgram
{
class Base
{
public double f(double i)
{
Console.Write("f (double): ");
return i + 3.3;
}
}
class Derived : Base
{
public int f(int i)
{
Console.Write("f (int): ");
return i + 3;
}
}
class Program
{
static void Main(string[] args)
{
Derived obj = new Derived();
Console.WriteLine(obj.f(3));
Console.WriteLine(obj.f(3.3));
}
}
}
Output: f(int) : 6 f(double) : 6.6
How it is possible?