Get all c# Types that implements an interface first but no derived classes

related to Getting all types that implement an interface we can easily get all Types in the Assembly that implements a specific interface.

Example:

interface IFace
{
}

class Face : IFace
{
}

class TwoFace : Face
{
}

For this structure, we will find both classes via reflection, i.e. all classes that are derived from the first implementation too, using

GetTypes().Where(
  type => type.GetInterfaces().Contains(typeof(IFace))
)

So the question is: how can I restrict the result to the base class that initially implements the interface?! In this example: only class type Face is relevant.

Jon Skeet
people
quotationmark

Firstly, I'd use Type.IsAssignableFrom rather than GetInterfaces, but then all you need to do is exclude types whose parent type is already in the set:

var allClasses = types.Where(type => typeof(IFace).IsAssignableFrom(type))
                      .ToList(); // Or use a HashSet, for better Contains perf.
var firstImplementations = allClasses
      .Except(allClasses.Where(t => allClasses.Contains(t.BaseType)));

Or as noted in comments, equivalently:

var firstImplementations = allClasses.Where(t => !allClasses.Contains(t.BaseType));

Note that this will not return a class which derives from a class which implements an interface, but reimplements it.

people

See more on this question at Stackoverflow