Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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.

like image 438
childno͡.de Avatar asked May 19 '14 10:05

childno͡.de


People also ask

What is the use of GETC in C?

The C library function int getc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. Declaration. Following is the declaration for getc() function. Parameters.

What is the ‘gets’ function in C programming?

Programs that use ‘gets’ can actually be a security problem on your computer. Since it is sometimes used in older code (which is why the GNU C Library still provides it), we need to understand how it is used. The gets function takes one parameter, the string in which to store the data which is read.

What is the difference between Getline and getdelim in C++?

The getdelim function is a more general form. getline stops reading input at the first newline character it encounters, however the getdelim function enables you to specify other delimiter characters than newline. In fact, getline simply calls getdelim and specifies that the delimiter character is a newline.

Why is ‘gets’ in C dangerous?

It is dangerous because it provides no protection against buffer overflow; overflowing the string into which it is saving data. Programs that use ‘gets’ can actually be a security problem on your computer. Since it is sometimes used in older code (which is why the GNU C Library still provides it), we need to understand how it is used.


1 Answers

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.

like image 57
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet