10

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?

nawfal
  • 70,104
  • 56
  • 326
  • 368
Dejan Stanič
  • 787
  • 7
  • 14

3 Answers3

12

Type.IsValueType should do the trick.

(pinched from here)

Community
  • 1
  • 1
Antony Koch
  • 2,043
  • 1
  • 16
  • 23
  • 1
    Thanks. I guess I'll also have to check for !IsPrimitive, but that should do the trick. – Dejan Stanič Feb 01 '10 at 11:40
  • 2
    @Dejan: also the primitives (such as boolean) are structs. – Fredrik Mörk Feb 01 '10 at 11:51
  • You're right, you'll need the !IsPrimitive. What about an Extension method? :D – OregonGhost Feb 01 '10 at 11:54
  • @Fredrik: Thanks, I know - but I need to check only for 'custom' structs, so I ended up with something like: return type.IsValueType && !type.IsPrimitive && type != typeof(Decimal); which works for this particular need. – Dejan Stanič Feb 01 '10 at 11:54
  • 1
    To work around things like typeof(Decimal), I decided for one project that I would exclude all types starting with "System." - this was the right thing to do in my project. Maybe it helps you. – OregonGhost Feb 01 '10 at 11:57
2

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;
}
nawfal
  • 70,104
  • 56
  • 326
  • 368
1

putting the comments on Antony Koch 's answer into an extention method:

public static class ReflectionExtensions {
        public static bool IsCustomValueType(this Type type) {            
               return type.IsValueType && !type.IsPrimitive && type.Namespace != null && !type.Namespace.StartsWith("System.");
        }
    }

should work

GreyCloud
  • 3,030
  • 5
  • 32
  • 47