Software Design Blog

Journey of Rinat Abdullin

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:

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");