I'm trying to set default property values for certain classes. Because the classes are generated automatically, I don't want to have to set them in the individual classes, so I created an extension method. It works great until I come across nullable properties, such as bool? properties because PropertyInfo.PropertyType
will not return bool. In fact, it's unclear to me what to test for when PropertyType
comes across a nullable bool.
Here's the outline of my method:
public static T SetDefaults<T>(this T model) where T : IModelClasses
{
//set values
foreach (PropertyInfo prop in model.GetType().GetProperties())
{
if (prop.PropertyType == typeof(string)) prop.SetValue(model, string.Empty, null);
else if (prop.PropertyType == typeof(bool)) prop.SetValue(model, false, null); //Will not set the property to false if the property is a nullable bool
...
}
return model;
}
I've looked into ways of getting the underlying type, such as below but the original object is required. Because PorpertyType
does not return the actual property, I cannot test it using this method:
private static Type GetType<T>(T obj)
{
return typeof(T);
}
Is there any way to evaluate the PropertyInfo
or ProperType
to determine if it is a bool? so that I can set it to false?