I have the following code:
public class Class1
{
void ValueSpecific(string arg)
{
// do string stuff
}
void ValueSpecific(int arg)
{
// do int stuff
}
void ValueSpecific(float arg)
{
// do float stuff
}
void ValueGeneric(string arg)
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
void ValueGeneric(int arg)
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
void ValueGeneric(float arg)
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
void Main(string s, int i, float f)
{
ValueGeneric(s);
ValueGeneric(i);
ValueGeneric(f);
}
}
This works but the bodys of all three overloads of ValueGeneric are identical. I want to amalgamate them into one method, which would look something like:
void ValueGeneric<T>(T arg) where T: string, float, int
{
// do stuff
ValueSpecific(arg);
// do more stuff
}
but this, of course, is not valid C#.
The best I can come up with is:
void ValueGeneric(object arg)
{
// Do stuff
if (arg is int)
{
ValueSpecific((int)arg);
}
else if (arg is string)
{
ValueSpecific((string)arg);
}
else if (arg is float)
{
ValueSpecific((float)arg);
}
else
{
Debug.Assert(false, "Invalid type)
}
// Do more stuff
}
but this seems very inelegant. I’d appreciate any suggestions. (While I would be interested in any solutions, one supported by .NET3.5 would be best, as that is what I am using.)
Assuming you’re doing the same stuff before and after in all of your overloads, you can apply the usual approach of factoring out what is different in the code and parameterize them. The only things that change are the argument that is passed in and the action that you perform on that argument. Pass them both in.
Then call the generic method using the appropriate action (your
ValueSpecificoverloads will resolve itself nicely).