Bart van Heukelom
Bart van Heukelom

Reputation: 44094

Getting the type of a "Type" in C# reflection

This is harder to find in the docs than I imagined. Anyway, I have some instances of Type. How can I find out if they represent classes, methods, interfaces, etc?

class Bla { ... }
typeof(Bla).GetKindOrWhatever() // need to get something like "Class"

(I'm using Mono on Linux but that shouldn't affect the question, I'm making portable code)

Upvotes: 1

Views: 1738

Answers (5)

Dr. Wily's Apprentice
Dr. Wily's Apprentice

Reputation: 10280

As others have mentioned, the Type class has various properties that you can use if you just need to know whether your type is a class, interface, delegate, etc.

If you have a Type object and you want to know if it is a specific type, then I recommend using the IsAssignableFrom method found on the Type class:

        Type objectType = obj.GetType();
        Type interfaceType = typeof(IExample);

        if (interfaceType.IsAssignableFrom(objectType))
        {
            //...
        }

Upvotes: 1

Martin Peck
Martin Peck

Reputation: 11544

Type.IsClass might help here. Also Type.IsInterface.

Check out... http://msdn.microsoft.com/en-us/library/system.type_members.aspx

There are quite a few "IsXxxx" properties on Type. Hopefully these will do what you want.

By the way, you should check out other questions on this subject on SO, including this one...

typeof(System.Enum).IsClass == false

... if the types you're going to be checking are enum types, as there are some strange (but predictable) results.

Upvotes: 9

Edgar Hernandez
Edgar Hernandez

Reputation: 4030

The Type class have some properties that are named IsXXX.
For example it has a IsEnum, IsClass, IsInterface.
If I understand correctly your question this is what you need

Upvotes: 1

fretje
fretje

Reputation: 8372

Type.IsClass Property?

Upvotes: 0

mkedobbs
mkedobbs

Reputation: 4375

There are a slew of properties off the Type class.

typeof(Bla).IsClass
typeof(Bla).IsInterface

etc.

http://msdn.microsoft.com/en-us/library/system.type_properties.aspx

Upvotes: 8

Related Questions