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


i have 2 functions same exact operation; since underlying api has overloaded fuction accept either string or int.

since using function, need call function either string or int. overloading way so? replicate code, beside signature of function; , seems 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 generic function; not sure if apply in case; never used them in past, , before dive in, thought worth ask around first.

you could use dynamic typing here:

// don't recommend - see later public void taketwo(dynamic value1, dynamic value2) {     baseapi.getvalues(value1, value2); } 

the overload resolution call getvalues performed @ execution time.

however:

  • there's no compile-time checking call taketwo valid
  • it less efficient (which may or may not significant; first point more important in cases)

you talk replicating code, in example you've shown all code method call. if there's other code in method genuinely common, i'd recommend extracting common code out , calling 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 want in both methods } 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -