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????)
var result =
partIndex = 0;
length = input.Length;
(length > 0)
var tempPartLength = length >= partLength ? partLength : length;
var part = input.Substring(partIndex * partLength, tempPartLength);
length -= partLength;
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
partLength = 30;
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