Find type of nullable properties via reflection
Solution 1:
possible solution:
propertyType = propertyInfo[propertyInfoIndex].PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
Solution 2:
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));
}
}
Solution 3:
foreach (var info in typeof(T).GetProperties())
{
var type = info.PropertyType;
var underlyingType = Nullable.GetUnderlyingType(type);
var returnType = underlyingType ?? type;
}
Solution 4:
As pointed out by Yves M. it is as simple as below.
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
{
var propType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var dataType = propType.Name;
}