Possible Duplicate:
Extension Methods vs Static Utility Class
I am building an API of general functions which perform actions based upon objects in .NET. For example; I have created a function that checks a string to see if it is an email address.
I could either have:
static bool IsEmailAddress(string text)
{
return IsMail(text);
}
or I could create an extension method that would be used like so:
string text = "[email protected]";
if (text.IsEmailAddress())
{
}
which is more suitable, or do you think since this is a general purpose library, I could technically implement it both ways and allow the developer to decide which is best for them?
Creating an extension method means that it will automatically show up during intellisense when a user uses that type. You have to be carefull not adding a lot of noise to the list of methods developers browse (especially when creating a reusable framework). For instance, when those methods are just usable in a certain context, you are probably better of using 'normal' static methods. Especially when implementing extension methods for general types such as string
.
Take for instance an ToXml(this string)
extension method, or an ToInt(this string)
extension methods. Although it seems pretty convenient to have these extension methods, converting text to XML is not something you will do throughout the application and it would be as easy to have do XmlHelper.ToXml(someString)
.
There is only one thing worse, and that is adding an extension method on object
.
If you're writing an reusable framework, the book Framework-Design-Guidelines by Krzysztof Cwalina is an absolute must read.