Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use extension methods, ext. methods vs. inheritance?

Tags:

c#

.net

People also ask

Why do we use extension methods?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

Is extension the same as inheritance?

Inheritance is nothing but extending a class and adding functionality to it. You can add properties (variables) as well as functions in the extending class.

What is Extensionmethod why the extension methods can we achieve the same thing using inheritance?

The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.


Times to use extension methods:

  • when you don't control the types being extended
  • where you don't want to force the implementor to provide code that can be done using the existing methods

For an example of the second point; you might have an extension method on IList<T> (for example, Sort) that can be written entirely using the existing IList<T> members... so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide much more functionality without breaking anything.

Times to not use extension methods:

  • when polymorphism is critical; you cannot guarantee that your code will be the version that gets executed with an extension method, as methods directly on the type take precedence
  • when you need access to private/protected members

Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:

  • Extension methods cannot be used to override existing methods

  • An extension method with the same name and signature as an instance method will not be called

  • The concept of extension methods cannot be applied to fields, properties or events

  • Use extension methods sparingly....overuse can be a bad thing!


This link http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/26/c-extension-methods---to-extend-or-not-to-extend.aspx provides good guidance on when to use Extension methods and when not.

To quote from this article:

A good extension method should:
- Apply to any possible instance of the type it extends.
- Simplify logic and improve readability/maintainability.
- Apply to the most specific type or interface applicable.
- Be isolated in a namespace so that it does not pollute IntelliSense.


I use extension methods when it makes sense. If you control a class and its code, you usually don't need extension methods.

If you don't, an extension method might be useful.

One place I frequently use extension methods is for [Flags] enumerations. When you have a flag-based enumeration, there's a rather large expression that's necessary to determine whether or not an enumeration value has a particular flag set. And so I build the following extension method whenever I build a [Flags] enumeration:

[Flags]
public enum MyEnum
{
    FlagA,
    FlagB,
    // etc.
}

public static class MyEnumExt
{
    public static bool HasFlags(this MyEnum item, MyEnum query)
    {
        return ((item & query) == query);
    }
}

That way my code looks like:

MyEnum flags = MyEnum.FlagA;
if(flags.HasFlags(MyEnum.FlagA))
{
  // handle FlagA
}

Rather than:

MyEnum flags = MyEnum.FlagA;
if((flags & MyEnum.FlagA) == MyEnum.FlagA)
{
  // handle FlagA
}

Honestly, I would say it is easier to explain when it is NOT a good idea than when it is a good idea.

I think, the main benefit to extension methods is that they may increase the adoption of your method. This is because the user will not have to instantiate an instance of another class in order to use your method and intellisense will advertise your method when a developer is looking for methods for the class you are extending. This could be important if you are trying to get other developers to follow a new standard in your company.

When contemplating whether or not to create an extension method, remember the SOLID principles.

Single Responsibility: - You are almost always at least bending the single responsibility principle with an extension method because you are tacking on to something that is already a class (that you either don't have control over or are too afraid to touch).

Open/Close Principle: - Extension methods cannot be overridden, which means your method may not be adequately "open for extension".

Liskov substitution principle: - If you have any sort of inheritance structure you will not be able to use the extension methods on the sub types.

Interface segregation principle: - Although you can "extend" an interface, you have to provide a concrete implementation for that extension. So you can not program towards an interface >that can be implemented differently in a different context (eg Unit Test)

Dependency inversion principle: - If your code has any dependencies, how are you going to expose those dependencies for factories and unit tests (dependency inversion principle)?

Finally, extension methods are just static methods wearing a new dress. So all of the difficulties with static methods (such as thread safety, garbage collection, etc) come along with extension methods when you implement them.

So, I would think long and hard about writing a method as an extension and reconsider using a factory and a basic helper class instead.

If you do write an extension method, please make it very simple. Try to avoid having any dependencies (or pass all of your dependencies in as parameters). And be careful for how you manage memory and lock resources in a multi-threaded environment.