Check If Type is a Nullable Type - Convert Nullable Type to Underlying Type - NullableConverter - C# 2.0 Generics

Check If Type is a Nullable Type - Convert Nullable Type to Underlying Type - C# 2.0 Generics

News Feed: David Hayden ( Sarasota Web Design and Development ), Filed: O/R Mappers, C# 2.0

 

When doing Object-Relational Mapping, Nullable Types are a beautiful thing. They allow you to support nullable columns in databases that map to a value type in the CLR. Examples of this may be DateTime and Int32 types that are allowed to be null in the database.

This morning I wanted to support this in my ActiveRecord Framework, which turned out to be much, much easier than anticipated. One of the challenges is verifying if a type ( class property in this case ) is a nullable type. Here is some C# code that does just that:

 

bool IsNullableType(Type theType)
{
    return (theType.IsGenericType && theType.
GetGenericTypeDefinition().Equals
(
typeof(Nullable<>))); }

 

You also may want to convert the Nullable Type to its Underlying Type. For example:

  • Convert DateTime? or Nullable<DateTime> to System.DateTime
  • Convert int? or Nullable<int> to System.Int32

 

The NullableConverter Class will allow you to convert a Nullable Type to its underlying type:

 

// UnderlyingType will equal System.DateTime
NullableConverter nc = new NullableConverter(DateTime?);
Type underlyingType = nc.UnderlyingType;

 

Good information if you are creating an O/R Mapper and need to support Nullable Types.

Related Post: C# Nullable Types - Lessen Impedance Mismatch of OOP and Relational Databases

 

Source: David Hayden ( Sarasota Web Design and Development )

Filed: O/R Mappers, C# 2.0

posted on Sunday, November 26, 2006 1:33 PM

Main

David Hayden Google +

David Hayden Twitter

Health & Fitness

JavaScript Patterns Book Review

HTML 5 and CSS3 - Develop with Tomorrow's Standards Today

Professional ASP.NET Design Patterns Book Review

Beginning Mac Programming Book Review

C# in Depth Book Review

ASP.NET MVC

Orchard CMS

Categories