William Jockusch William Jockusch - 2 months ago 11
C# Question

Method overload and type conversion

I have two C# conversion methods:

public int MyConvertToInteger(double x) {
if (x > int.MaxValue) {
return int.MaxValue;
} else if (x < int.MinValue || double.IsNaN(x)) {
return int.MinValue;
} else {
return (int)x;
}
}

public int MyConvertToInteger(string str) {
if (str == null) {
return 0;
}
return str.Length;
}


and one business method, with two possible types for each argument, resulting in four overloads:

public int IntSum(int x, int y) {
unchecked {
return x+y;
}
}

public int IntSum(int x, string y) {
int iy = MyConvertToInteger(y);
return IntSum(x, iy);
}

public int IntSum(double x, int y) {
int ix = MyConvertToInteger(x);
return IntSum(ix, y);
}

public int IntSum(double x, string y) {
int ix = MyConvertToInteger(x);
return IntSum(ix, y);
}


That is annoying but practical. However, If I were to add a third argument with two possible types, we would be up to eight overloads, which IMO is beyond the pale.

I am wondering if there is a way to somehow specify the possible conversions in the method argument, so that we don't get this profusion of overloads? (I am not interested in "solutions" which involve taking arguments of a more general type such as "object", then inspecting the type of whatever is passed in.)

Answer

Well,

I am wondering if there is a way to somehow specify the possible conversions in the method argument, so that we don't get this profusion of overloads?

No. It's not possible in C#.

Sometimes it's essential to create many overloads especially when performance is at stake. I've seen projects with something like 50 overloads created for one method. What is possible however is to run more strict overloads from more generic ones, in other words Sum(x ,y, z) overload can run two (x, y) + (y, z) so there no real need to write any other logic inside of more generic overloads just to re-use one that already exist.

The only other option is to accept params object[] and determine what types we work with, create composite types, or usedynamic's .

Comments