I want use reflection for get properties type. this is my code
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
model.
This is an old question, but I ran into this as well. I like @Igoy's answer, but it doesn't work if the type is an array of a nullable type. This is my extension method to handle any combination of nullable/generic and array. Hopefully it will be useful to someone with the same question.
public static string GetDisplayName(this Type t)
{
if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
return string.Format("{0}?", GetDisplayName(t.GetGenericArguments()[0]));
if(t.IsGenericType)
return string.Format("{0}<{1}>",
t.Name.Remove(t.Name.IndexOf('`')),
string.Join(",",t.GetGenericArguments().Select(at => at.GetDisplayName())));
if(t.IsArray)
return string.Format("{0}[{1}]",
GetDisplayName(t.GetElementType()),
new string(',', t.GetArrayRank()-1));
return t.Name;
}
This will handle cases as complicated as this:
typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName()
Returns:
Dictionary<Int32[,,],Boolean?[][]>
Change your code to look for nullable type, in that case take PropertyType as the first generic argument:
var propertyType = propertyInfo.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = propertyType.GetGenericArguments()[0];
}
model.ModelProperties.Add(new KeyValuePair<Type, string>
(propertyType.Name,propertyInfo.Name));