.net - Do C# extension methods affect the current instance or return a new object of the same type? -


when extend non-static type extension method, work performed on "this" happen original instance of extended class, or return new instance changes applied? or can either, depending on how extension method written?

consider example extension method:

public static addressentity fromaddresslight(this addressentity addressentity, addresslight addresslight) {     if (addresslight == null)     {         return null;     }      var result = new addressentity     {         id = addresslight.addressid,         addressname = addresslight.addressname,         // other mapping conversions here     };      return result; } 

which of following ways of calling work?

addresslight light = new addresslight(); // assume constructor populates addressentity myentity = new addressentity(); // constructor not populate  myentity.fromaddresslight(light); // cause myentity take on value of "result" in extension method?... myentity = myentity.fromaddresslight(light); // ... or needed copy "result" myentity?  // ... , why not visual studio allows? not become static member of extended class? myentity = addressentity.fromaddresslight(light); 

thats kind of odd extension method (makes more sense "normal" static method) here goes, in order of lines (skipping first two):

  1. this nothing. extension method returns new object, not assigned anything, , falls out of scope , garbage collected.

  2. this think, , "reasonable" way use method.

  3. this isn't allowed because there no instance of "addressentity" being passed function. not explicitly (obviously pass 1 argument) or implicitly (because used type access it, not object).

especially because trying (3), not have function extension method (it doesn't use of addressentity field, why take type?) , have normal static method instead.

to answer question (in title) explicitly:

an extension method isn't special, has implicit argument (the "this" argument) looks nice when calling it. if returns new value, you'll new value. if modify "this" argument, modifies existing value. both no problem. depends on content of extension method.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -