Reputation: 411
I want to loop through the properties of my class and get each properties type. I got it most of the way, but when trying to get the type, instead of getting string, int, etc, I get the type reflection. Any ideas? Let me know if more background information is needed. Thanks!
using System.Reflection;
Type oClassType = this.GetType(); //I'm calling this inside the class
PropertyInfo[] oClassProperties = oClassType.GetProperties();
foreach (PropertyInfo prop in oClassProperties) //Loop thru properties works fine
{
if (Nullable.GetUnderlyingType(prop.GetType()) == typeof(int))
//should be integer type but prop.GetType() returns System.Reflection
else if (Nullable.GetUnderlyingType(prop.GetType()) == typeof(string))
//should be string type but prop.GetType() returns System.Reflection
.
.
.
}
Upvotes: 2
Views: 2965
Reputation: 1064224
Firstly, you can't use prop.GetType()
here - that is the type of the PropertyInfo - you mean prop.PropertyType
.
Secondly, try:
var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
this will work whether it is nullable or non-nullable, since GetUnderlyingType will return null
if it isn't Nullable<T>
.
Then, after that:
if(type == typeof(int)) {...}
else if(type == typeof(string)) {...}
or alternative:
switch(Type.GetTypeCode(type)) {
case TypeCode.Int32: /* ... */ break;
case TypeCode.String: /* ... */ break;
...
}
Upvotes: 14
Reputation: 25895
Use the PropertyType property.
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.propertytype
Upvotes: 1
Reputation: 42276
You're almost there. The PropertyInfo
class has a property PropertyType
which returns the type of the property. When you call GetType()
on the PropertyInfo
instance you are actually just getting the RuntimePropertyInfo
which is the type of the member you are reflecting upon.
So, to get the Type of all the member Properties, you would just have to do something like:
oClassType.GetProperties().Select(p => p.PropertyType)
Upvotes: 3