Posted By: phreaks | Oct 7th @ 11:06 AM
page 1 of 1
Comments: 2 | Views: 425
phreaks
phreaks
Messiah of Marxism
Is it possible to do dynamic type casting in C#?

Say I have an overloaded method that takes an int or double param, but the param comes from a typed dataset that can contain a DBNULL. Just calling MyDataSet.myTable.MyField will throw an InvalidCastException when the underlying value in the DS is null.

I don't want to check each iteration for IsMyFieldNull, how can I deal with this?

I thought that if I could do some dynamic casting I could solve the problem, by returning an Empty String, but I can't.

Something like this: (Which obviously won't compile):


public static Object HandleDBNull(Object value)

{

if (value.Equals(DBNull.Value))

{

return String.Empty;

}

else

{

return value;

}

}





PerfectPhase
PerfectPhase
"This is not war, this is pest control!" - Dalek to Cyberman

How about some hackery like this

     static void Main(string[] args)
      {
         DataSet1 ds = new DataSet1 () ;
         DataSet1.DataTable1Row row = ds.DataTable1.NewDataTable1Row () ; 
         double? fred = HandleDbNull<double> ( () => row.DoubleColumn);
         string bob = HandleDbNull<string>(() => row.StringColumn);
      }

      static Nullable<T> HandleDbNull<T>(Func<ValueType> work) where T : struct
      {
         ValueType vt;
         try
         {
            vt = work();
         }
         catch (StrongTypingException)
         {
            return null;
         }
         return (T)vt ;   //do this just to make sure that the type of T and the column match and errors aren't hidden by the catch
      }

      static T HandleDbNull<T>(Func<object> work) where T : class
      {
         try
         {
            return (T)work();
         }
         catch (StrongTypingException)
         {
            return null;
         }
      }


Something I started a while back and will get round to finishing when I finish my current project is a PostSharp aspect that can create extra nullable properties on a typed dataRow for all the value types on that row.

P.S.  or you can include the LINQ DataSetExtensions and do row.Field<double?>("DoubleColumn") but you lose using the property from the typed dataset.

static string HandleDBNull(object o)
{
    return (o == DBNull.Value) ? string.Empty : o as string;
}

If it is okay that o must be a class:

static T HandleDBNull<T>(object o) where T : class
{
    return o == DBNull.Value ? default(T) : o as T;
}
page 1 of 1
Comments: 2 | Views: 425