3

How do I check is the type class or struct?

 protected   T GetNullValue<T>(IDataReader reader, int ordinalId)
    {
        if (reader.IsDBNull(ordinalId))
        {
            //if T is struct.....
            //else if I is class
        }
        return (T)reader.GetValue(ordinalId);
    }
Alexandre
  • 13,030
  • 35
  • 114
  • 173
  • You may find this answer helpful: http://stackoverflow.com/questions/2713900/how-to-determine-if-a-net-type-is-a-custom-struct – Aim Kai Mar 07 '11 at 17:54
  • 2
    @Aim - I'm not so sure of that. The accepted answer is particularly bad in my opinion. – ChaosPandion Mar 07 '11 at 17:55
  • it is bad form to tack on another question on your existing question like that. It makes the existing answers invalid and the whole post confusing for people later on. – C. Ross Mar 07 '11 at 19:15

3 Answers3

7
if (default(T) is ValueType)
   ...

is the most efficient thing I can come up with at the moment.

user541686
  • 205,094
  • 128
  • 528
  • 886
3

Get the Type class for the object, and check it.

Type t = reader.GetValue(ordinalId).GetType();
if (t.IsValueType){
    //Struct
} else { 
    //Class
}

I suspect you will be using the Type object later on in your code, if you're trying to dynamically handle the results.

C. Ross
  • 31,137
  • 42
  • 147
  • 238
  • That code won't compile. You can't use `typeof` with an object instance, you have to use `GetType()` – thecoop Mar 07 '11 at 20:21
2

If T is a value type, it cannot be null. To make a value type nullable, you have to use the System.Nullable struct.

tugudum
  • 387
  • 1
  • 4