I examine the properties of an object via reflection and continue processing the data type of each property. Here is my (reduced) source:
private void ExamineObject(object o)
{
Type type = default(Type);
Type propertyType = default(Type);
PropertyInfo[] propertyInfo = null;
type = o.GetType();
propertyInfo = type.GetProperties(BindingFlags.GetProperty |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
// Loop over all properties
for (int propertyInfoIndex = 0; propertyInfoIndex <= propertyInfo.Length - 1; propertyInfoIndex++)
{
propertyType = propertyInfo[propertyInfoIndex].PropertyType;
}
}
My problem is, that I newly need to handle nullable properties, but I have no clue how to get the type of a nullable property.
possible solution:
propertyType = propertyInfo[propertyInfoIndex].PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
Nullable.GetUnderlyingType(fi.FieldType)
will do the work for you check below code for do the thing you want
System.Reflection.FieldInfo[] fieldsInfos = typeof(NullWeAre).GetFields();
foreach (System.Reflection.FieldInfo fi in fieldsInfos)
{
if (fi.FieldType.IsGenericType
&& fi.FieldType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// We are dealing with a generic type that is nullable
Console.WriteLine("Name: {0}, Type: {1}", fi.Name, Nullable.GetUnderlyingType(fi.FieldType));
}
}
foreach (var info in typeof(T).GetProperties())
{
var type = info.PropertyType;
var underlyingType = Nullable.GetUnderlyingType(type);
var returnType = underlyingType ?? type;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With