How to check programmatically if a type is a struct or a class?
Use Type.IsValueType
:
Gets a value indicating whether the Type is a value type.
Use it either like this:
typeof(Foo).IsValueType
or at execution time like this:
fooInstance.GetType().IsValueType
Conversely there is also a Type.IsClass
property (which should have been called IsReferenceType
in my opinion but no matter) which may or may not be more appropriate for your uses based on what you are testing for.
Code always seems to read better without boolean negations, so use whichever helps the readability of your code.
As Stefan points out below, in order to properly identify structs you must be careful to avoid false positives when it comes to enums
. An enum
is a value type so the IsValueType
property will return true
for enums
as well as structs
.
So if you truly are looking for structs
and not just value types in general you will need to do this:
Type fooType = fooInstance.GetType();
Boolean isStruct = fooType.IsValueType && !fooType.IsEnum;
Type type = typeof(Foo);
bool isStruct = type.IsValueType && !type.IsPrimitive;
bool isClass = type.IsClass;
It could still be: a primitive type or an interface.
Edit: There is a lot of discussion about the definition of a struct. A struct and a value type are actually the same, so IsValueType
is the correct answer. I usually had to know whether a type is a user defined struct, this means a type which is implemented using the keyword struct
and not a primitive type. So I keep my answer for everyone who has the same problem then me.
Edit 2: According to the C# Reference, enums are not structs, while any other value type is. Therefore, the correct answer how to determine if a type is a struct is:
bool isStruct = type.IsValueType && !type.IsEnum;
IMHO, the definition of a struct is more confusing then logical. I actually doubt that this definition is of any relevance in praxis.