Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know when an interface is directly implemented in a type ignoring inherited ones?

The issue appears is when I have a class implementing an interface, and extending a class which implements an interface:

class Some : SomeBase, ISome {}
class SomeBase : ISomeBase {}
interface ISome{}
interface ISomeBase{}

Since typeof(Some).GetInterfaces() returns and array with ISome and ISomeBase, i'm not able to distinguish if ISome is implemented or inherited (as ISomeBase). As MSDN I can't assume the order of the interfaces in the array, hence I'm lost. The method typeof(Some).GetInterfaceMap() does not distinguish them either.

like image 696
Diego Gonzalez Avatar asked Oct 23 '09 14:10

Diego Gonzalez


People also ask

Is it necessary to implement all methods of an interface in C#?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.

How interface methods are implemented in C#?

On implementation of an interface, you must override all of its methods. Interfaces can contain properties and methods, but not fields/variables. Interface members are by default abstract and public. An interface cannot contain a constructor (as it cannot be used to create objects)

What type is an interface C#?

Some of the interface types in C# include. IEnumerable − Base interface for all generic collections. IList − A generic interface implemented by the arrays and the list type. IDictionary − A dictionary collection.


1 Answers

You just need to exclude the interfaces implemented by the base type :

public static class TypeExtensions
{
    public static IEnumerable<Type> GetInterfaces(this Type type, bool includeInherited)
    {
        if (includeInherited || type.BaseType == null)
            return type.GetInterfaces();
        else
            return type.GetInterfaces().Except(type.BaseType.GetInterfaces());
    }
}

...


foreach(Type ifc in typeof(Some).GetInterfaces(false))
{
    Console.WriteLine(ifc);
}
like image 128
Thomas Levesque Avatar answered Nov 03 '22 01:11

Thomas Levesque