Creating a strongly typed instance of an Object (including Nullable types)

Ever since 2.0 released Nullables, it's made my life a lot easier, particularly in terms of database operations.

If you haven't used Nullables yet, it's a pretty easy concept to grasp. Say for instance you have a boolean. It has two states - true & false. You can then declare this primitive type as a Nullable, which means it then has three states - true, false & null.

The syntax for this is pretty simple, it's just a matter of adding a question mark (?) as such:

bool? nullableBool = null;

you can also do:

Nullable<bool> nullableBool = null;

Why would you want to use Nullables though? If you've ever integrated your app with a database, chances are you've come across the situation where your database would have a bit/bool field that allows nulls. This means that you then have three states for your data, ie: true, false, null - which is exactly what we have in 2.0+

So what happens if you retrieve an object out of a database, and are trying to dynamically fill a business objects that take advantage of nullables? The trick to instanciating nullable objects through reflections is the snippet:

typeof(Nullable<>).MakeGenericType(typeof(bool))

Which will create a new type of bool? (ie: Nullable<bool>). From here, you simply need to call the GetConstructor().Invoke() on this type, to create an instance of this Nullable type.

To illustrate this point, here's

    object myObject = objFromDatabase;

    Type boTypeParam = businessObjectType

 

    #region Determine if value is wrapped in Nullable<>

    bool isNullable = (boParamType.IsGenericType && boParamType.GetGenericTypeDefinition() == typeof(Nullable<>));

 

    if (isNullable)

        propertyType = Nullable.GetUnderlyingType(boParamType);

    #endregion

 

    object instanceVal = myObject;

 

    if(isNullable)

    {

        if (boParamType.IsEnum)

            instanceVal = Enum.ToObject(boParamType, myObject);

 

        Type nullableType = typeof(Nullable<>).MakeGenericType(boParamType);

        instanceVal = nullableType.GetConstructor(new Type[] { boParamType}).Invoke(new object[] { instanceVal });

    }

 

    property.SetValue(objectToPopulate, instanceVal, null);

Nullable types are extremely useful, particularly when it comes to database operations. You can use them on other primitive types including bool, int, long, short, decimal, float etc, which will help you avoid doing things such as subclassing those primitives to create your own pseudo-nullable classes, or resorting to representing null numeric values through use of "-1" or .MIN_VALUE etc.

Creating Nullable<> types and setting their values dynamically through reflections can cut down the amount of repetitive code you have to write, particularly when creating your business objects dynamically from datasets or other data sources.

«November»
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678