Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How can I check if a Type is concrete?

Tags:

c#

types

I have a collection of Types and I want to filter out every Type that is not concrete.

I can see that I can check isAbstract and isInterface to catch most non-concretes, but is this going to miss anything?

Is there an "isConcrete" property?

like image 733
Vesuvian Avatar asked Sep 12 '14 15:09

Vesuvian


2 Answers

I guess that if you give a IsClass && !IsAbstract a try this could work?

if isConcreteType(myType) { DoSomething(); }

bool isConcreteType(Type type) { 
    return type.IsClass && !type.IsAbstract && !type.IsInterface;
}

As per comment by KC-NH:

Structs are value types and so IsClass will be false. Do you want structs to be considered concrete classes? If so, remove the IsClass condition

So if you want to consider a struct a concrete type, you have to wave away the IsClass constraint.

bool isConcreteType(Type type) { return !type.IsAbstract && !type.IsInterfaces; }
like image 93
Will Marcouiller Avatar answered Sep 21 '22 15:09

Will Marcouiller


The opposite of IsAbstract is "is concrete", so you're good with those checks

like image 31
KC-NH Avatar answered Sep 18 '22 15:09

KC-NH