Saturday
Jan102009
How to Find Extension Methods Targeting Object?
As may already know, it is generally not a good idea to create .NET extension methods that target objects:
// this is bad
public static bool CheckNull(this object self)
{
if (object == null)
throw new InvalidOperationException("Object can't be null");
}
There are at least two reasons for that:
- Targeting object "pollutes" auto-completion options of every single variable in your favorite IDE (Intellisense for VS).
- VB.NET does not support extending objects anyway.
This simple NUnit unit test will detect any methods that extend object:
var methods = codebase.Methods
.Where(m => m.Has<ExtensionAttribute>())
.Where(m => m.Parameters[0].Is<object>());
CollectionAssert.IsEmpty(methods.ToArray());
Codebase class could be found in the Lokad.Quality.dll from the latest Lokad Shared Libraries; it is initiated like:
var codebase = new Codebase("Assembly1.dll","Assembly2.dll");
Comments Off
Saturday, January 10, 2009 at 15:55