Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check programmatically if a type is a struct or a class?

How to check programmatically if a type is a struct or a class?

like image 410
Jader Dias Avatar asked Dec 01 '09 16:12

Jader Dias


People also ask

Is struct in C#?

In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.

Is string a struct or class?

Swift takes a different approach: strings are structs, and in fact come packed with functionality. Almost all of Swift's core types are implemented as structs, including strings, integers, arrays, dictionaries, and even Booleans.

Is struct and class same?

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.


1 Answers

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; 
like image 123
Andrew Hare Avatar answered Oct 07 '22 22:10

Andrew Hare