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?
For an application programmer, extension methods are an incredibly powerful and expressive tool. They enable convenience, extensibility, and an improved intellisence experience. However, many of the features that make extension methods so useful for library consumers can be problematic for class library authors.
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.
In object-oriented programming, a helper class is used to assist in providing some functionality, which isn't the main goal of the application or class in which it is used. An instance of a helper class is called a helper object (for example, in the delegation pattern).
Actually I'm answering the question of why extension methods cannot work with static classes. The answer is because extension methods are compiled into static methods that cannot recieve a reference to a static class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With