Go to home page mail me! RSS Feed
FoxMetrics Web Analytics

Get underlying type from a nullable type

Tuesday, March 11, 2008 11:33 AM

As my forever quest for simple & reusable code keeps growing, I stumble across some bottlenecks once in a while.

Anyway, I have a simple class that is called "PopulateObjectFromFormRequest" and as descriptive as the name is, it does one simple yet helpful task. Given an object as a generic type I.e (user) and a web form as a parameter I.e (aspnetform), it will scan through all the controls of that web form and use reflection on the object and assign values to the object properties that matches controls from within the form.

How does this help me? Well if I my web page that has a registration form and I have a class or struct that needs to be populated with that data, I simply use that class. It prevents me from writing code that fills up an object with data from the web. Therefore, one less task to complete and 5000 less lines of code to write.

What's the problem now? Well, for starters, since I use reflection to determine the type, if the object properties is a nullable type, reflection.GetType() does not equate to typeof(Int32). Therefore, I need to determine if the type of what I'm reflecting is a generic type and nullable, and if it is, I need to drill further down to find the underlying type.

Using SubSonic or DatabaseFly, the datatype for a database column that is of a DateTime and Nullable is DateTime? - whoops, my cool class will fail to determine and assign to the appropriate property or field. Alright, straight to some code and enough talking.

 

#region [ TestUnderlyingTypes ]
internal class NullWeAre
{
    // Create a direct none nullable type variable
    public DateTime TodaysDate;

    // Create a nullable type variable
    public DateTime? DateOfBirth;

    // Create another nullable type
    public Int32? MyAge;

    // Oh, what the heck, through in a string
    public string Name = "Rydal Williams";
}

/// <summary>
/// Method: TestUnderlyingTypes
/// </summary>
public static void TestUnderlyingTypes()
{
    // Test class
    NullWeAre nwa = new NullWeAre();
                           
    // Ok, now lets see how we can get the underlying type
    // Lets perform some reflection on our test class
    //************************************************************************
    System.Reflection.FieldInfo[] fieldsInfos = typeof(NullWeAre).GetFields();
    foreach (System.Reflection.FieldInfo fi in fieldsInfos)
    {
        if (fi.FieldType.IsGenericType
            && fi.FieldType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            // We are dealing with a generic type that is nullable
            Console.WriteLine("Name: {0}, Type: {1}", fi.Name, Nullable.GetUnderlyingType(fi.FieldType));
        }
        else
        {
            // Ok, its just one of those basic data types
            Console.WriteLine("Name: {0}, Type: {1}", fi.Name, fi.FieldType);
        }                
    }
}
#endregion

Your Comments.

  • # re: Get underlying type from a nullable type

    GravatarThanks so much for posting this. Spent ages trying to figure out how to determine the underlying type of a Nullable variable until I read your piece.

    Left by Developer in London at 3/28/2008 1:41 PM
  • # re: Get underlying type from a nullable type

    GravatarThanks for posting this article...you saved me a lot of work trying to figure this out myself.

    Left by Rich at 1/12/2009 9:45 AM
  • # re: Get underlying type from a nullable type

    Gravatar
    static void Main(string[] args)
    {
    Nullable<int> n = 0;
    int i = 0;

    Console.WriteLine(IsGeneric(n));
    Console.WriteLine(IsGeneric(i));

    Console.ReadLine();
    }

    public static bool IsGeneric (Nullable<int> n)
    {
    return true;
    }
    public static bool IsGeneric (int i)
    {
    return false;
    }

    Left by carpptn at 3/8/2009 6:35 AM
  • # re: Get underlying type from a nullable type

    GravatarThat was inspiring,

    Keep up the good work,

    Thanks for bringing this up





    www.geeks.ltd.uk/.../...plication-Development.html

    Left by web development at 10/26/2009 12:11 PM
  • # re: Get underlying type from a nullable type

    GravatarFantastic, I was looking for
    Nullable.GetUnderlyingType(type)

    Genius.

    Left by Daev at 11/18/2009 6:00 AM

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 1 and 4 and type the answer here:

Preview Your Comment.

 
Next entries »