Saturday, May 4, 2013

Extension Method Insanity!!!

Extension methods are something I've known about for a while, but I have realized some new things in their practice recently that make them only that much more fascinating.  The first thing is to understand exactly what they are.  An extension method is "actually" a static method where the first argument designates it being available as an instance method.  Here is a snippet of one for syntax.

The above snippet is a simple extension that can be called on ANY IEnumerable<T> to wrap it within a TSList object(this is just a thread safe list I created).  Pretty cool, but doesn't do much.  This is way I would use them mainly when I first discovered them.  It works well to reduce code lines a good bit.

RECENT DISCOVERY #1

So, given that extension methods are trully static methods, we can actually call them on any field/property that matchs the first argument type.  The value CAN be null!!!  This works well in a few other cases.  Here's another snippet of a simple use case.


So, the above extensions allow any  event handler to be called using one line instead of the normal two to ensure it's not null.  Yawn.... these two examples are really not that exciting.

RECENT DISCOVERY #2

Extensions can actually be used to do incredible things with reinstantiating objects, and thread safety during that change.  In the snippet below I am taking an array, we don't need to know what kind, and resizing it while maintaining thread safety.  There are other extension methods for pulling the values etc. while utilizing the same thread safety techniques.



The using brackets are due to a Smartlock class I use which is instantiated by the CreateLock EXTENSION method on objects with the ICollection interface.  If you review this closely you should see that it pulses both the previous lock and the new lock when a new array is created.  It does this to ensure that the other thread safe extensions will be pulsed if needed one way or another.  (This has been tested for stability with success).

RECENT DISCOVERY #3

Ok, this is where things get a little more interesting and becomes that much more useful with all the above practices considered as well.  Using polymorphing types extension methods can be used to change objects state and type in method chains.  I don't have quite enough space here to really showcase the whole thing, but my posting isn't a tutorial anyway, just something to think about.



When looking at this one note that it doesn't always return the same object.  It may return a "MultiSelector" or the argument passed.  There are others to force return of the parent or a child etc etc.  Methods like the first ToList example make this less fantastic, it just shows a more clear example of how extreme this can go.  If you study up on interfaces and polymorphism you can do amazing things with extension methods.  Like converting Enums to arrays.  That one is really fun =)

No comments:

Post a Comment