Find the type of null properties through reflection

I examine the properties of an object through reflection and continue to process 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 recently need to handle properties with NULL capability, but I don't know how to get the property type is nullable.

+53
reflection c # nullable
Apr 13 2018-11-11T00:
source share
5 answers

Possible Solution:

  propertyType = propertyInfo[propertyInfoIndex].PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = propertyType.GetGenericArguments()[0]; } 
+93
Apr 13 2018-11-11T00:
source share

Nullable.GetUnderlyingType(fi.FieldType) will do the work for you to check the code below to do what 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)); } } 
+33
Apr 13 2018-11-11T00:
source share
 foreach (var info in typeof(T).GetProperties()) { var type = info.PropertyType; var underlyingType = Nullable.GetUnderlyingType(type); var returnType = underlyingType ?? type; } 
+11
Jul 11 '13 at 9:23
source share

This method is simple, fast and safe.

 public static class PropertyInfoExtension { public static bool IsNullableProperty(this PropertyInfo propertyInfo) => propertyInfo.PropertyType.Name.IndexOf("Nullable`", StringComparison.Ordinal) > -1; } 
+1
Sep 14 '17 at 21:43 on
source share

I use a loop to go through all the properties of the class to get the type of the property. I am using the following code:

 public Dictionary<string, string> GetClassFields(TEntity obj) { Dictionary<string, string> dctClassFields = new Dictionary<string, string>(); foreach (PropertyInfo property in obj.GetType().GetProperties()) { if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && property.PropertyType.GetGenericArguments().Length > 0) dctClassFields.Add(property.Name, property.PropertyType.GetGenericArguments()[0].FullName); else dctClassFields.Add(property.Name, property.PropertyType.FullName); } return dctClassFields; } 
0
Aug 08 '17 at 8:48 on
source share



All Articles