Servy said in a comment:
Don't make the method generic if it's not actually generic, and don't say the method can accept any type if it can't in fact accept any type. As you've already been told, if you want to handle a finite number of specific types, have overloads for each of those types.
to which you replied:
Alas, I showed the teacher, but he said that it was not that. He said that it should be something like an abstract calculator where for each type T you can define the operation N
You can have your method with that signature and no if
blocks at all, but the Add
method can't be static. You have to pass in a Func<T1, T2, TResult>
where T1
, T2
, and TResult
are the same (T
):
public class Calculator<T>
{
private readonly Func<T, T, T> _func;
public Calculator(Func<T, T, T> func)
{
_func = func;
}
public T Add(T a, T b)
{
return _func(a, b);
}
}
You'd use it like this:
Func<int, int, int> intAddition = (a, b) => a + b;
var intCalculator = new Calculator<int>(intAddition);
Console.WriteLine(intCalculator.Add(1, 2)); // writes 3
Func<string, string, string> stringAddition = (a, b) => a + b;
var stringCalculator = new Calculator<string>(stringAddition);
Console.WriteLine(stringCalculator.Add("Hello ", "world")); // writes "Hello world"
Online example: https://dotnetfiddle.net/8NOBsv
This way you get to specify the logic of the Add
method, and you don't have loads of overloaded methods (or awful type-checking logic inside the method like if ( typeof(T) == typeof(string) )
, etc.