Let's make a list of answers where you post your excellent and favorite extension methods.
The requirement is that the full code must be posted and a example and an explanation on how to use it.
Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on Codeplex.
Please mark your answers with an acceptance to put the code in the Codeplex project.
Please post the full sourcecode and not a link.
Codeplex News:
24.08.2010 The Codeplex page is now here: http://extensionoverflow.codeplex.com/
11.11.2008 XmlSerialize / XmlDeserialize is now Implemented and Unit Tested.
11.11.2008 There is still room for more developers. ;-) Join NOW!
11.11.2008 Third contributer joined ExtensionOverflow, welcome to BKristensen
11.11.2008 FormatWith is now Implemented and Unit Tested.
09.11.2008 Second contributer joined ExtensionOverflow. welcome to chakrit.
09.11.2008 We need more developers. ;-)
09.11.2008 ThrowIfArgumentIsNull in now Implemented and Unit Tested on Codeplex.
I have an extension method for logging exceptions:
And it is used like this:
[sorry for posting twice; the 2nd one is better designed :-)]
Example:
The ThrowIfArgumentIsNull is a nice way to do that null check we all should do.
Below is the way to use it and it works on all classes in your namespace or wherever you use the namespace its within.
It's ok to use this code on the CodePlex project.
I got tired of tedious null-checking while pulling values from MySqlDataReader, so:
Of course this could be used with any SqlDataReader.
Both hangy and Joe had some good comments on how to do this, and I have since had an opportunity to implement something similar in a different context, so here is another version:
This one is for MVC it adds the ability to generate a
<label />
tag to theHtml
variable that is available in everyViewPage
. Hopefully it will be of use to others trying to develop similar extensions.Use:
Output:
Code:
I have various extension methods in my MiscUtil project (full source is available there - I'm not going to repeat it here). My favourites, some of which involve other classes (such as ranges):
Date and time stuff - mostly for unit tests. Not sure I'd use them in production :)
Ranges and stepping - massive thanks to Marc Gravell for his operator stuff to make this possible:
Comparisons:
Argument checking:
LINQ to XML applied to anonymous types (or other types with appropriate properties):
Push LINQ - would take too long to explain here, but search for it.