Overload is the only way to add different parameter to the same function?

I have 2 functions that does the same exact operation; since the underlying API has an overloaded fuction that accept either a string or an int.

Since I am using this function, I need to call the function either with a string or with an int. Is overloading the only way to do so? I replicate the code, beside the signature of the function; and it seems a waste of code.

public void taketwo(int value1, int value2)
{
    // Other operations happen here
    baseAPI.getvalues(value1, value2);
}

public void taketwo(string val1_str, string val2_str)
{
    // Other operations happen here
    baseAPI.getvalues(val1_str, val2_str);
}

I recall something about generic function; but I am not sure if that would apply in this case; I never used them in the past, and before dive in, I thought that it was worth to ask around first.

Jon Skeet
people
quotationmark

You could use dynamic typing here:

// I don't recommend you do this - see later
public void TakeTwo(dynamic value1, dynamic value2)
{
    baseAPI.GetValues(value1, value2);
}

The overload resolution for the call to GetValues will then be performed at execution time.

However:

  • There's no compile-time checking that your call to TakeTwo will be valid
  • It is less efficient (which may or may not be significant; the first point is more important in most cases)

You talk about replicating code, but in the example you've shown all the code is the method call. If there's other code in the method which is genuinely common, I'd recommend extracting that common code out and calling it in both overloads:

public void TakeTwo(int value1, int value2)
{
    CommonCode();
    baseAPI.GetValues(value1, value2);
}

public void TakeTwo(string value1, string value2)
{
    CommonCode();
    baseAPI.GetValues(value1, value2);
}

private void CommonCode()
{
    // Things you want to do in both methods
}

people

See more on this question at Stackoverflow