Read Catalogue
One: Duplicate code
Two: Eliminate duplicate code by delegating func in C #
One: Duplicate code
1 Public classpersion2 {3 Public stringName {Get;Set; }4 Public intAge {Get;Set; }5 6 Publicpersion getpersioninfo ()7 {8 Try9 {TenPersion persion =Newpersion (); OnePersion. Name ="David"; APersion. Age = -; - - returnpersion; the } - Catch(Exception ex) - { - return NULL; + } - } +}
1 Public classEmployee2 {3 Public stringPost {Get;Set; }4 Public intSalary {Get;Set; }5 6 PublicEmployee getemployeeinfo ()7 {8 Try9 {TenEmployee Employee =NewEmployee (); OneEmployee. Post ="Development"; AEmployee. Salary = the; - - returnemployee; the } - Catch(Exception ex) - { - return NULL; + } - } +}
Two: Eliminate duplicate code by delegating func in C #
The Try Catch statement is only one time, as shown below, eliminating the Getpersioninfo method and the Try Catch statement for Getemployeeinfo
1 Public classutillity2 {3 Public StaticT tryexecute<t> (func<t> Func,stringmethodName)4 {5 Try6 {7 returnfunc ();8 }9 Catch(Exception ex)Ten { OneConsole.WriteLine ("MethodName:"+ MethodName +"Error:"+Ex. Message); A return default(T); - } - } the}
1 Public classpersion2 {3 Public stringName {Get;Set; }4 Public intAge {Get;Set; }5 6 Publicpersion getpersioninfo ()7 {8 returnUtillity.tryexecute<persion> (() =9 {TenPersion persion =Newpersion (); OnePersion. Name ="David"; APersion. Age = -; - - returnpersion; the } -,"Getpersioninfo"); - } -}
1 Public classEmployee2 {3 Public stringPost {Get;Set; }4 Public intSalary {Get;Set; }5 6 PublicEmployee getemployeeinfo ()7 {8 returnUtillity.tryexecute (() =9 {TenEmployee Employee =NewEmployee (); OneEmployee. Post ="Development"; AEmployee. Salary = the; - - returnemployee; the } -,"Getemployeeinfo"); - - } +}
1 class Program2 {3 Static voidMain (string[] args)4 {5Persion Persion1 =Newpersion ();6Persion Persion2 =Persion1. Getpersioninfo ();7 8Console.WriteLine ("This persion name is {0}", Persion2. Name);9Console.WriteLine ("This persion age is {0}", Persion2. Age);Ten OneEmployee employee1 =NewEmployee (); AEmployee Employee2 =employee1. Getemployeeinfo (); - -Console.WriteLine ("This employee post is {0}", Employee2. Post); theConsole.WriteLine ("This employee salary is {0}", Employee2. Salary); - - console.readline (); - } +}
De-Duplicated code in 2.c# by delegating func