Following is a test class
public class Test
{
public int a;
}
Following are the Extension methods I 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 the following calls lead to same result for t.a, which is 10
:
t.Do1(5)
t = t.Do2(5)
There are many instances in my code where I need to implement a similar logic, which one is better, one of them is passing reference by value and internally updating it, other is returning the updated reference. Is using one of them safer, if this kind of code ever gets into multi threaded wrapper, provided all the thread safety is taken care of. Normally to update the referenced variable we need a ref or out keyword, which is like pointer to a pointer, instead of a separate pointer to same memory location as in this case, but here in extension methods, I cannot use them. Please let me know if the question needs further clarity
In your example it does not make sense to return the
t
variable.t
is a reference, so settingt.a
updates the object already. There's no need forref
,out
or returningt
. One reason for returningt
would be to allow you to use method chaining.You only need
ref
orout
if you want to actually change the reference, not the content of the reference.