7

For a Type, there is a property IsClass, but how to know a Type is a struct?

Sorry, I have to add some more information.

  1. I am using C#.
  2. Although IsValueType is a necessary condition, it is obviously not enough. For an Integer is a value type also.
nawfal
  • 70,104
  • 56
  • 326
  • 368
Ying
  • 71
  • 3
  • possible duplicate of [How to decide a Type is a custom struct?](http://stackoverflow.com/questions/2296288/how-to-decide-a-type-is-a-custom-struct) – nawfal Apr 19 '13 at 22:09

6 Answers6

10
t.IsValueType && !t.IsPrimitive && !t.IsEnum;
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
  • I dont' get the reason of `!t.IsPrimitive`. `Boolean`, `Byte`, `Char`, `Double` (etc...) are not structs? – Paolo Moretti Dec 20 '11 at 12:21
  • 2
    Sometimes in C# we count them as such, because they're value types, but `struct` comes from "structured", referring to structs' composite nature (normally having more than one field, though 0 or 1 is permissable) and the origin of the keyword back in C, though C# and C structs are different in several ways. It's clear from the question that the OP was thinking the latter way rather than the former. This view doesn't take a "turtles all the way down" perspective, but takes the units that can't be broken down any further, to not be structs. – Jon Hanna Dec 20 '11 at 14:06
3

If you are talking about c#, you can use the IsValueType property.

Clinton
  • 2,787
  • 1
  • 18
  • 10
1

If it's a value type (e.g., a struct), use Type.IsValueType.

John Feminella
  • 303,634
  • 46
  • 339
  • 357
1

You can use IsValueType.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
0

Well then, I guess for your requirement then this comes close:

bool isStruct = myType.IsValueType && !myType.IsPrimitive;

but still DateTime isn't covered by that for example. Maybe you would have to add further types you want to exlude manually.

herzmeister
  • 11,101
  • 2
  • 41
  • 51
  • 2
    DateTime gives the correct result of true with this code. It's enums that it doesn't handle correctly. – Jon Hanna Aug 18 '10 at 12:09
-1

use this:

 x.GetType().IsValueType();

From help:

Type::IsValueType Property Gets a value indicating whether the Type is a value type. Value types are types that are represented as sequences of bits; value types are not classes or interfaces. Value types are referred to as "structs" in some programming languages. Enums are a special case of value types.

user218447
  • 659
  • 5
  • 5
  • Types have different meanings when applied to storage location than when applied to heap objects. Under the hood, every value type has an associated heap type. Casting a value type to `Object` or to an interface that it implements will create a new heap object whose fields are copied from the value-type instance being cast. Calling `GetType` on a value type will cast it to `Object` first, since value types don't have the type-destrictor field required by `GetType`. – supercat Oct 05 '12 at 03:09