Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if Type is a struct?

Given a PropertyInfo instance, which has a Type property, how does one determine if it is a struct? I found there are properties such as IsPrimitive, IsInterface, etc. but I'm not sure how to ask for a struct?

EDIT: To clarify question. Suppose I have a method:

public Boolean Check(PropertyInfo pi)
{
   return pi.Type.IsStruct;
}

What do I write instead of IsStruct?

like image 865
Dejan Stanič Avatar asked Feb 01 '10 11:02

Dejan Stanič


People also ask

What type is a struct C#?

C# - Struct. In C#, struct is the value type data type that represents data structures. It can contain a parameterized constructor, static constructor, constants, fields, methods, properties, indexers, operators, events, and nested types.

How do you check if an object is a specific type?

To determine whether an object is a specific type, you can use your language's type comparison keyword or construct.

Is a struct a value or reference type?

However, unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct , whereas a variable of a class type contains a reference to the data, the latter known as an object.

Is Int a struct in C#?

So a struct is a value type, and because a int is a value type it is also a struct. And class is a reference type. I know de differences between reference types and value type.


1 Answers

Structs and enums (IsEnum) fall under the superset called value types (IsValueType). Primitive types (IsPrimitive) are a subset of struct. Which means all primitive types are structs but not vice versa; for eg, int is a primitive type as well as struct, but decimal is only a struct, not a primitive type.

So you see the only missing property there is that of a struct. Easy to write one:

public bool IsStruct(this Type type)
{
   return type.IsValueType && !type.IsEnum;
}
like image 58
nawfal Avatar answered Oct 17 '22 20:10

nawfal