There is a certain class. In a number of methods of this class, the first and last lines are the same. Is there some elegant way to write them somewhere only once and use them as a wrapper for these methods, so as not to duplicate the code in the methods each time? Even if it takes more lines of code, the main thing is to have the opportunity to change the code in only one place, and the logic of work would change in all such methods. Below is an example of two methods.

public bool Draw(int firstLine = 1, int lastLine = 180) { if (!this.Connected || drv == null) return false; ////// drv.FirstLineNumber = firstLine; drv.LastLineNumber = lastLine; OperationResult = drv.Draw(); return OperationResult == 0 ? true : false; ////// } public bool XReport() { if (!this.Connected || drv == null) return false; ////// OperationResult = drv.PrintReportWithoutCleaning(); return OperationResult == 0 ? true : false; ////// } 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

Like that:

 public bool Draw(int firstLine = 1, int lastLine = 180) { return RunWithDrv(() => { drv.FirstLineNumber = firstLine; drv.LastLineNumber = lastLine; return drv.Draw(); }); } public bool XReport() { return RunWithDrv(drv.PrintReportWithoutCleaning); } public bool RunWithDrv(Func<int> action) { if (!this.Connected || drv == null) return false; ////// OperationResult = action(); return OperationResult == 0 ? true : false; ////// } 

    Alternatively, you can look towards aspect-oriented programming: AspectSharp, PostSharp