Why use C # extension methods?

21

What do I get with extension methods that I do not gain with inheritance?

Simply using it as if it had the same name is tricky, since it causes more confusion than anything else.

    
asked by anonymous 24.06.2016 / 13:43

4 answers

15

You have a question that answers in part what is being asked here: Java 8 "default method" versus C # "extend method ". I will not repeat what is already there.

Extension method has nothing to do with inheritance. In fact inheritance usage is abused and should be avoided whenever possible .

Extension methods do not add behavior to a class. They are unrelated utility methods that work primarily with one data type. It is just a syntactic sugar in static methods out of classes and there is an inheritance relationship. So it has disadvantages quoted in the linked question above.

All modern languages are providing extensibility mechanisms better than inheritance after realizing that the latter does not deliver the wonders they preached in the beginning. Inheritance is still useful where polymorphism is needed and reuse as well.

  • Gives a syntax more fluent than static methods, which even helps IDE help you.

  • Win the reduction of functionality coupling. It reduces the need to use design patterns to get this kind of advantage (okay, this can only be achieved with static methods, but this is more convenient). Inheritance is one of the worst coupling types .

  • Gets the ability to add features just without inheriting. Multiple types can not even be inherited ( structs , sealed , and enum - example ). Inheritance would be inadequate in others. So it's used more to add functionality to something that already exists and you do not have or do not want to have control.

  • Lets you link methods to interfaces. This is very powerful, especially considering that it is often best to program for interfaces . Increases reuse.

  • Lets you choose (depending on how it was written) at the time of use whether it will be available for your code or not. For example, if you do not add System.Linq to your code, LINQ methods do not pollute the possibilities of using methods.

  • It is the basis of LINQ . O in extension methods would be extremely complex and there would be a lot of incompatibility to create it. That's a huge gain.

Confusing extra method names

One of the things you should avoid is to not place the static class of the extension method (s) in the same namespace that the type it is extending. This will make the extension method always available for that type. Of course it can be useful and do this, but only do it if you are sure it will be advantageous.

If you just want the extension method to be available when you choose, just create it in a separate namespace and then only with its import (with using ) that the method will be available. >

For example, avoid creating one:

namespace System {
    public static class ObjectExt {
        pubic static bool IsNull(this object source) {
            return source == null;
        }
    }
}

This will make all objects of all types have this method, always!

Every resource can be abused. Do not abuse it.

If you pick up something that has abused you and disturbs you, consider switching from "supplier."

Conclusion

Remembering that object access in an extension method does not have access privileges for non-public members. What can be good even in most cases. But it can bring some difficulty in others.

There is controversy over whether inheritance or extension methods should be used as standard when possible.

Examples of use:

Using interface:

static Random r = new Random(DateTime.Now.Millisecond);
public static void Shuffle<T>(this IList<T> list, int lowerItem, int upperItem) {
    upperItem = upperItem > list.Count ? list.Count : upperItem;
    lowerItem = lowerItem < 0 ? 0 : lowerItem;
    for (int i = lowerItem; i < upperItem; i++) {
        int j = r.Next(i, upperItem);
        T tmp = list[j];
        list[j] = list[i];
        list[i] = tmp;
    }
}

Site with several useful methods , some abused.

    
24.06.2016 / 13:58
11

Extension methods allow you to add a method to a class without creating a new derived type, some classes can not be inherited as the String class and Structs types.

You may want to count, for example, how many words you have in a string and for that

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

and to use

using ExtensionMethods;

string s = "Hello Extension Methods";
int i = s.WordCount();             // com extension
int j = MyExtensions.WordCount(s); // sem extension
    
24.06.2016 / 13:57
4

A point I have not seen anyone approach, and a bit more technical, is a type of code-bloating that consumes more memory than desirable.

The more a class has members defined, the greater is the amount of metadata stored in memory that is needed to represent the existence of the type. These metadata are needed regardless of whether or not reflection is used, at least in part, because of the Garbage Collector. This in turn uses the object type information to be able to navigate the object graph and be able to clear those that are not referenced by any other object, so it needs to know the memory layout of each type.

Increasing the amount of metadata is not necessarily bad, but a problem arises when using generics. A generic type like List<T> that over the years has been gaining more and more members, is that whenever a new type List<T1> ... List<Tn> is defined, a new portion of memory is allocated to store the metadata of that type, because each object instance points to its metadata. Each time the generic type increases, this increase is multiplied by all the different specific uses of the generic type, so if you start using too much memory with metadata only.

The extension methods came in good time to stop the need to expand these types, so that they all remain very stable since this feature was introduced.

    
21.07.2016 / 23:28
2

Let's go to something practical, for an uncomplicated understanding!

You have to do certain operation on an object type several times, for example, clear a string and leave only the numbers, right!

Instead of building a class with a method, and calling this to the object that needs the treatment, an extension of this type is created, which will always be available on this object throughout your system!

public static string OnlyNumbers(this string str)
{
    List<char> numbers = new List<char>("0123456789");
    StringBuilder toReturn = new StringBuilder(str.Length);
    CharEnumerator enumerator = str.GetEnumerator();

    while (enumerator.MoveNext())
    {
        if (numbers.Contains(enumerator.Current))
            toReturn.Append(enumerator.Current);
    }
    return toReturn.ToString();
}

In this case we return the new value of this string where it only has numbers!

Business is, certain action is done repeatedly for a type of object, so it is more practical to create an extended method of that type!

Application

string telefone = telefonePosted.OnlyNumbers();
    
21.07.2016 / 22:13