c# - Unboxing and casting in one statement in generic method -
i have little utility method looks so:
/// <summary> /// replaces dbnull value default of type specified /// </summary> /// <typeparam name="t">resulting type</typeparam> /// <param name="p_this">object check dbnull</param> /// <returns>p_this if not dbnull.value, else default(t)</returns> public static t replacedbnullwithdefault<t>(this object p_this) { return p_this == system.dbnull.value ? default(t) : (t)p_this; }
in specific scenario, taking record out of data table , taking specific field out of using weak types, , specific field i'm getting long
being boxed object
. example reproduces follows:
var obj = 2934l; int num = obj.replacedbnullwithdefault<int>();
it fails invalidcastexception
, @ (t)p_this
.
i understand why, boxed long
cannot cast directly int
, , trying fails:
object mylong = 234l; int myint = (int)mylong;
however, unboxing , casting works fine:
object mylong = 234l; int myint = (int)(long)mylong;
how can work around in method?
you can try this:
public static t replacedbnullwithdefault<t>(this object p_this) t : struct { return p_this == system.dbnull.value ? default(t) : (t)convert.changetype(p_this, typeof(t)); }
nevertheless exception if try apply function not-convertible type.
so better cast value manually known type.
Comments
Post a Comment