Extension Method

hello everybody,

Extension method are not well know but they are very powerfull.

This article is not a tutorial with extension method but an inventory around it.

When use it

Extension method must be use only for technical issues never for business requirement.

For example, you have a string and you want to split it into list of fix lenght substring (Why MS doesn’t includes in the box????)

public static class StringExtensions{    
    public static List<string> SplitIntoParts(this string input, int partLength)
    {        var result = new List<string>();
        int partIndex = 0;
        int length = input.Length;
        while (length > 0)
{
            var tempPartLength = length >= partLength ? partLength : length;
            var part = input.Substring(partIndex * partLength, tempPartLength);
            result.Add(part);
            partIndex++;
            length -= partLength;}
        return result;
    }

}
And the manner how we call it

string longString = "This is a very long string, which we want to
 split on smaller parts every max. 30 characters long."; // Length: 98
var partLength = 30;
var parts = longString.SplitIntoParts(partLength);

How implement it

As I said previously, extensions are designed for technicals cases. The extension’s code shall not exceed ten or twenty lines.

In Visual Studio,  I recommend to store extensions in one project dedicated. This project can be referenced in each artifact.

Moreover, you can manage your extensions near your client project, in fact String.SpliintParts method should be the same in your client A and your client B, so manage your extensions in your own project.

Where do I can find extensions method

I recommend a great site http://extensionmethod.net/

It includes not only .NET extensions, but don’t use all extensions without reading the code. Make sure you understand what it does, and all methods may not bug free