In an interview they had asked an Question like this
there are three overloading methods
public int Addtoatal(int a, int b)
public int Addtoatal(int a, int b, int c)
public float Addtoatal(float a, float b)
is there any way i can write down one method where i can send an int or float as an parameter to the method ,can we really do any thing like this in OOPS
any help would be great
Thanks
Yes, using generics:
If the method needs to use any operators (+,-,*) etc. it will be problematic because generic types can’t ensure that the class T has the operator (operators can’t be declared in interfaces, and therefor you can’t make a constraint to match).
In .Net 4.0 you could use dynamic typing to get a dynamic variable to contain the result and add to it:
In other .Net versions you’ll need a work around like the Operator class in MiscUtils: generic method to add int, float, in c#
The second example with the three parameters would need to have a different signature (in .Net 2.0) because it has more parameters.
in .Net 4.0 you could just use optional parameters for generic types, but can’t do it for value types:
But you could use boxing with nullable types, this would work with int and double:
Now the next best thing you could do, if you don’t want to use generics, is have a single method declaration as double (C# 4.0, because of the optional parameter):
In this example the int values will be converted to a double anyway, so there’s no loss of data, and the int can implicitly converted to double, but the return value would need to be explicitly cast to int.