Blog from Saravanan Arumugam

Let us talk about Technologies

Identify Nullable Types


I had a need of using the reflection to go through different properties of a class and examine if it is a nullable type.

I have learned an interesting thing that GetType() method upon the property would not let us know if it is a nullable type. Moreover, there is no direct method in reflection to check that up, (like IsVisible or IsValueType).

I found an interesting write up from MSDN that explained the issues I faced and posted a solution to it as well.

 

How to: Identify a Nullable Type (C# Programming Guide)

 

The following code lets us know if it is a Nullable type. But before that we need to get the type from non-GetType() way.

 

                foreach (var property in typeof(Request).GetProperties())
                {
                    Type type = property.PropertyType;
                    
                    //Check the value of non nullable fields
                    if (type.Is.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        
                    }
                }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: