4

Is it possible to check if the type, which is stored in PropertyInfo, is primitive?

For example I want to do this:

 // from and to are both objects declared in the parameters.
 Type fType = from.GetType();
 Type tType = to.GetType();

 PropertyInfo[] fmpi = fType.GetProperties();
 PropertyInfo[] tmpi = tType.GetProperties();

 foreach(var pi in  tmpi)
 {
     if (pi.CanWrite)
     {
         var fpi = fmpi.SingleOrDefault(item => item.Name.ToLower() == pi.Name.ToLower());

         if (pi.GetType().IsPrimitive || pi.GetType() == typeof(string))
         {
             pi.SetValue(to, fpi.GetValue(from, null));
         }
     }
 }

Whenever I execute this code It doesn't go through the if statemenet. The main reason is that whenever I do pi.GetType() it says that it's a PropertyInfo. This is quite obvious since it's declared as a PropertyInfo. But I hope you get the idea.

I have also discovered that pi.PropertyType.Name contains the name of the actual type of the property. Is there anyway I can execute IsPrimitive on this property? If not, is there any work around which let's me do something like this?

I checked out How To Test if Type is Primitive but in this situation the user is using a direct type and I'm using PropertyInfo.

Nashmár
  • 392
  • 1
  • 7
  • 22
Berend Hulshof
  • 1,039
  • 1
  • 16
  • 36

1 Answers1

12

The main reason is that whenever I do pi.GetType() it says that it's a PropertyInfo.

You should use PropertyType property of PropertyInfo instead of using GetType() method.

Excerpt from documentation:

Gets the type of this property.

So instead of

pi.GetType().IsPrimitive 

use this

pi.PropertyType.IsPrimitive 
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69