Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert [TYPE] to nullable<[TYPE]> in C#?

Question:

I wrote a method to retrieve a SQL result as a list of a class instead of a datatable. The problem is, I have a int field in the database, which is nullable.

If I hit a row with a NULL int, DataReader returns DbNull.Value instead of null. So System.Convert.ChangeType(objVal, fi.FieldType) throws an exception, because it can't convert DbNull to an int.

So far so bad. I thought I had solved the problem, when I just compared objVal to DbNull.Value and if true, did this instead: System.Convert.ChangeType(null, fi.FieldType)

unfortunately, I just realized, the resulting integer type is 0 instead of NULL.

So I just tried changing the int type in my class to Nullable<int>, but now I have the problem that when a value is not DbNull.Value, ChangeType throws an exception because it can't convert int to nullable<int>...

So now I try to detect the type of the object returned by datareader, and convert it to a nullable value.

tTypeForNullable is correctly shown as Nullable<int>. But when I look at the result type, I get: int.

Why is that ? And more important: How can I do that properly ?

Please note that because type is an object, I can't use a generic method to create Nullable<int>.

bool bisnull = IsNullable(objVal);
bool bisnullt = IsNullable(fi.FieldType);

if (bisnullt)
{
    Type tTypeForNullable = typeof(Nullable<>).MakeGenericType(objVal.GetType());

    //object result = Activator.CreateInstance(tTypeForNullable, new object[] { objVal });
    //object result = Activator.CreateInstance(typeof(Nullable<int>), new object[] { objVal });
    object result = Activator.CreateInstance(tTypeForNullable, objVal);
    Type tres = result.GetType();
    fi.SetValue(tThisValue, System.Convert.ChangeType(result, fi.FieldType));
}

Here's the complete routine for reference:

public virtual System.Collections.Generic.IList<T> GetList<T>(System.Data.IDbCommand cmd)
        {
            System.Collections.Generic.List<T> lsReturnValue = new System.Collections.Generic.List<T>();
            T tThisValue = default(T);
            Type t = typeof(T);

            lock (cmd)
            {
                using (System.Data.IDataReader idr = ExecuteReader(cmd))
                {

                    lock (idr)
                    {

                        while (idr.Read())
                        {
                            //idr.GetOrdinal("")
                            tThisValue = Activator.CreateInstance<T>();

                            // Console.WriteLine(idr.FieldCount);
                            for (int i = 0; i < idr.FieldCount; ++i)
                            {
                                string strName = idr.GetName(i);
                                object objVal = idr.GetValue(i);


                                System.Reflection.FieldInfo fi = t.GetField(strName);
                                //Type tttttt = fi.FieldType;
                                if (fi != null)
                                {
                                    //fi.SetValue(tThisValue, System.Convert.ChangeType(objVal, fi.FieldType));
                                    if (objVal == System.DBNull.Value)
                                    {
                                        objVal = null;
                                        fi.SetValue(tThisValue, null);
                                    }
                                    else
                                    {
                                        //System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(fi.FieldType);

                                        bool bisnull = IsNullable(objVal);
                                        bool bisnullt = IsNullable(fi.FieldType);

                                        if (bisnullt)
                                        {
                                            Type tTypeForNullable = typeof(Nullable<>).MakeGenericType(objVal.GetType());

                                            //object result = Activator.CreateInstance(tTypeForNullable, new object[] { objVal });
                                            //object result = Activator.CreateInstance(typeof(Nullable<int>), new object[] { objVal });
                                            object result = Activator.CreateInstance(tTypeForNullable, objVal);
                                            Type tres = result.GetType();
                                            fi.SetValue(tThisValue, System.Convert.ChangeType(result, fi.FieldType));
                                        }
                                        fi.SetValue(tThisValue, System.Convert.ChangeType(objVal, fi.FieldType));
                                    }
                                }
                                else
                                {
                                    System.Reflection.PropertyInfo pi = t.GetProperty(strName);
                                    if (pi != null)
                                    {
                                        //pi.SetValue(tThisValue, System.Convert.ChangeType(objVal, pi.PropertyType), null);


                                        if (objVal == System.DBNull.Value)
                                        {
                                            objVal = null;
                                            pi.SetValue(tThisValue, null, null);
                                        }
                                        else
                                        {
                                            pi.SetValue(tThisValue, System.Convert.ChangeType(objVal, pi.PropertyType), null);
                                        }


                                    }
                                    // Else silently ignore value
                                } // End else of if (fi != null)

                                //Console.WriteLine(strName);
                            } // Next i

                            lsReturnValue.Add(tThisValue);
                        } // Whend

                        idr.Close();
                    } // End Lock idr

                } // End Using idr

            } // End lock cmd

            return lsReturnValue;
        } // End Function GetList

with this:

public System.Data.IDataReader ExecuteReader(System.Data.IDbCommand cmd)
        {
            System.Data.IDataReader idr = null;

            lock(cmd)
            {
                System.Data.IDbConnection idbc = GetConnection();
                cmd.Connection = idbc;

                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                    cmd.Connection.Open();

                idr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            } // End Lock cmd

            return idr;
        } // End Function ExecuteReader

Please note that because type is an object, I can't use a generic method to create Nullable<int>.

like image 702
Stefan Steiger Avatar asked Oct 23 '22 19:10

Stefan Steiger


1 Answers

You're boxing - and the result of a boxing operation for a nullable value type is never a boxed value of that type. It's either null or a non-nullable value type. See MSDN for more information.

like image 172
Jon Skeet Avatar answered Oct 26 '22 23:10

Jon Skeet