Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find type of nullable properties via reflection

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.

like image 277
user705274 Avatar asked Apr 13 '11 04:04

user705274


3 Answers

possible solution:

    propertyType = propertyInfo[propertyInfoIndex].PropertyType;
    if (propertyType.IsGenericType &&
        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
      propertyType = propertyType.GetGenericArguments()[0];
    }
like image 72
Markus Avatar answered Oct 22 '22 10:10

Markus


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));
            }

    }
like image 38
Pranay Rana Avatar answered Oct 22 '22 10:10

Pranay Rana


foreach (var info in typeof(T).GetProperties())
{
  var type = info.PropertyType;
  var underlyingType = Nullable.GetUnderlyingType(type);
  var returnType = underlyingType ?? type;
}
like image 39
Minh Giang Avatar answered Oct 22 '22 10:10

Minh Giang