c# 4.0 - Code duplication issue inside an if -
i have code duplication want avoid cannot create method containing code because there slight difference in line inside if. here's mean :
code 1 :
if case1 () { same code if() { same code line1 } code 2 :
if case2 () { same code if() { same code line2 } both codes same except 1 line (line1 , line2). since code big want be able copy inside function example. have idea how this?
thanks
generally speaking, looking action or func. that's type encapsulates executable code:
public int yourcommonmethod(int parameter, func<int, int> calculate) { // common code if(calculationneeded) { // common code result = calculate(parameter); } // more common code } you call 2 different calculation methods:
int result = yourcommonmethod(5, => + 17); or
int result = yourcommonmethod(5, => / 48); for action, need less:
public int yourcommonmethod(int parameter, action<int> dowork) { // common code if(calculationneeded) { // common code dowork(parameter); } // more common code } and can call this:
int result = yourcommonmethod(5, console.writeline); or
int result = yourcommonmethod(5, => console.writeline("some string including {0}", i));
Comments
Post a Comment