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 t
variable. 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
Post a Comment