Reputation: 314
I'm trying to iterate over an Enumerable collection of mix of nullable types However I want to compare the nullable type with a intrinsic type such as string or decimal. i.e. Here is a snippet
<% foreach (PropertyInfo prop in this.Columns)
{ %>
<td>
<% var typeCode = Type.GetTypeCode(prop.PropertyType); %>
<%-- String Columns --%>
<% if (typeCode == TypeCode.String)
{ %> ....
prop.PropertyType is of type 'datetime?', however var typeCode is 'object'.So when i compare typeCode to TypeCode.String, it fails. Is there a way to resolve a nullable type to it's underlying type? , e.g resolve datetime? to datetime.
Upvotes: 1
Views: 1177
Reputation: 269358
You can use the static Nullable.GetUndlerlyingType
method. I would probably wrap it in an extension method for ease of use:
public static Type GetUnderlyingType(this Type source)
{
if (source.IsGenericType
&& (source.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
// source is a Nullable type so return its underlying type
return Nullable.GetUnderlyingType(source);
}
// source isn't a Nullable type so just return the original type
return source;
}
You'll need to change your example code to look something like this:
<% var typeCode = Type.GetTypeCode(prop.PropertyType.GetUnderlyingType()); %>
Upvotes: 4