c# - Extension methods, which is a better choice -


following test class

public class test {    public int a; } 

following extension methods have created:

public static class extension {       public static void do1(this test t,int value)   {      t.a = t.a + value;   }    public static test do2(this test t,int value)   {      t.a = t.a + value;      return t   } } 

code usage:

test t = new test(); t.a = 5; 

both following calls lead same result t.a, 10:

t.do1(5)  t = t.do2(5) 

there many instances in code need implement similar logic, 1 better, 1 of them passing reference value , internally updating it, other returning updated reference. using 1 of them safer, if kind of code ever gets multi threaded wrapper, provided thread safety taken care of. update referenced variable need ref or out keyword, pointer pointer, instead of separate pointer same memory location in case, here in extension methods, cannot use them. please let me know if question needs further clarity

in example not make sense return tvariable. t reference, setting t.a updates object already. there's no need ref, out or returning t. 1 reason returning t allow use method chaining.

you need ref or out if want change reference, not content of reference.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -