DrFloyd5
DrFloyd5

Reputation: 13787

Given an Object, How can I programatically tell what Interfaces it supports?

Given this:

Interface IBase {string X {get;set;}}
Interface ISuper {string Y {get;set;}}

class Base : IBase {etc...}
class Super : Base, ISuper {etc...}

void Questionable (Base b) {
  Console.WriteLine ("The class supports the following interfaces... ")
  // The Magic Happens Here
}

What can I replace "The Magic" with to display the supported interfaces on object b?

Yes, I know by being of class Base it supports "IBase", the real hierarchy is more complex that this. :)

Thanks! -DF5

EDIT: Now that I've seen the answer I feel stupid for not tripping over that via Intellisense. :)

Thanks All! -DF5

Upvotes: 2

Views: 377

Answers (4)

JaredPar
JaredPar

Reputation: 755269

Heh, I saw the Console.WriteLine and thought you were looking for a string representation. Here it is anyways

public string GetInterfacesAsString(Type type) { 
  return type.GetInterfaces().Select(t => t.ToString()).Aggregate(x,y => x + "," + y);
}

Upvotes: 2

Diadistis
Diadistis

Reputation: 12174

The Magic :

foreach (Type iface in b.GetType().GetInterfaces())
    Console.WriteLine(iface.Name);

Upvotes: 8

Matt Hamilton
Matt Hamilton

Reputation: 204239

foreach (var t in b.GetType().GetInterfaces())
{
    Console.WriteLine(t.ToString());
}

Upvotes: 2

Ilya Ryzhenkov
Ilya Ryzhenkov

Reputation: 12142

b.GetType().GetInterfaces()

Upvotes: 8

Related Questions