简体   繁体   中英

Extension methods, which is a better choice

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 ta, 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 setting ta updates the object already. There's no need for ref , out or returning t . One reason for returning t would be to allow you to use method chaining.

You only need ref or out if you want to actually change the reference, not the content of the reference.

You are actually misunderstanding sense of ref and out keywords. Those are used, if you want to replace whole referenced object inside your method, for simple property level update they are not needed at all.

In your example, as Test is a class (reference type), there is no actual difference between two methods, but returning initial Test object as in Do2 method is just pointless, as object was already updated. So best of two will be the first implementation:

public static class Extension
{    
     public static void Do1(this Test t,int value)
     {
         t.a = t.a + value;
      }
}

Going back to Do2 method - as I said before, referenced object value is already updated inside a method, so there is even no point in assigning return value to initial variable:

t.Do2(5)

is the same as

t.Do(5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM