Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide a Type is a custom struct?

Tags:

c#

struct

For a Type, there is a property IsClass in C#, but how to decide a Type is a struct?

Although IsValueType is a necessary condition, it is obviously not enough. For an int is a value type also.

Someone suggests the following code:

bool IsStruct = type.IsValueType && !type.IsEnum && !type.IsPrimitive;

But I am not sure whether it is an accurate method. The formula should tell the difference between struct and other types such as DateTime, int and arrays.

As some friends have pointed out that here, I mean user defined struct and not predefined types, such as DateTime.

like image 875
Ying Avatar asked Feb 19 '10 12:02

Ying


People also ask

Is Int a struct in C#?

5, the simple types provided by C#, such as int , double , and bool , are, in fact, all struct types.

Can a struct be null C#?

In C# a struct is a 'value type', which can't be null.

Can a struct have methods C#?

Features of C# StructuresStructures can have methods, fields, indexers, properties, operator methods, and events.


2 Answers

Technically, an int is also a struct. IsPrimitive just checks if the type is one of the primitive types the CLR handles a little differently. You should be fine with the suggestion IsValueType && !IsEnum && !IsPrimitive.

If you want only custom structs (i.e. those not supplied by the BCL), you may have luck excluding types with a FullName that starts with "System.", or only including the ones you're interested in by filtering by assembly or namespace, or use a custom attribute.

like image 77
OregonGhost Avatar answered Oct 04 '22 20:10

OregonGhost


Should be at least

bool isStruct = type.IsValueType && !type.IsEnum &&
               !type.IsPrimitive && type != typeof(decimal);
like image 24
Lu55 Avatar answered Oct 04 '22 20:10

Lu55