I am wondering that why the following scenario is not working in c#.
class a
{
public int add(int a, int b)
{
return a + b;
}
public string add(int c, int d)
{
return "String : "+(c + d).ToString();
}
}
Since the following is working fine (in the case of inheritance)
class a
{
public int add(int a, int b)
{
return a + b;
}
}
class b : a
{
public string add(int c, int d)
{
return "String : "+(c + d).ToString();
}
}
Here if I am creating an object of b
and b.add(1,2)
returns String:3
n both case two add
method having different return type ( am aware that against method overloading) , but it working fine in the case of inheritance but not in single class.
Anybody knows the reason?
In the first example (both methods within one single class), no overloading can take place as the signatures of both methods are the same (only name and parameter types count, return value is ignored). This results in a compiler error.
In the second example, the method add with return type string
hides the inherited method. When you have something like
a myB = new b();
myB.add(1,2);
Then the implementation of the base class will be called even if the actual type is b. For
b myB = new b();
myB.add(3,4);
the implementation of b gets called (look at the variable type of myB, it is important!).