views:

254

answers:

4

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

+8  A: 

b.GetType().GetInterfaces()

Ilya Ryzhenkov
+2  A: 
foreach (var t in b.GetType().GetInterfaces())
{
    Console.WriteLine(t.ToString());
}
Matt Hamilton
Is there any good reason to prefer var over Type? I tend to avoid var as much as possible but without good justification...
Diadistis
Diadistis, search for "to var or not to var".
Ilya Ryzhenkov
I always use var in foreach loops unless I'm iterating over a collection that doesn't implement IEnumerable<T>. The call to "GetInterfaces" makes it clear what type "t" is in this example, so why bother repeating it in the declaration? (IMHO)
Matt Hamilton
+2  A: 

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);
}
JaredPar
GetInterfaces returns all interfaces, not only immediate.
Ilya Ryzhenkov
Thanks, didn't realize that. I'll update the answer
JaredPar
That's not entirely correct either :) You have to deal with nested interfaces, which should be converted from CLR to C# notation.
Ilya Ryzhenkov
@Ilya, picky picky :). What about interfaces which are entirely unrepresentable in C#? For intance <>Foo is a legal interface name.
JaredPar
@JaredPar, Well, not just picky :) I wanted to put some attention to the topic of what is the purpose of constructing comma-delimited list of interfaces, how this list is going to be used and what sense does it make.
Ilya Ryzhenkov
@Ilya, definately agree on the need to understand intent. There are lots of issues that come once you start trying to convert metadata/reflection back into a real langauge. See deccompiled F# for example
JaredPar
@JaredPar, yeah, I know, We make ReSharper ;)
Ilya Ryzhenkov
+8  A: 

The Magic :

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