C#: How to cast a value from a database field to an explicit typed variable
In fact, I've already found the answer to my question, here at stackoverflow. But because of my low reputation, I can't give thank to the person (Richard Petheram) who gave me the hint. So please add me the votes to 15 so I could at least thank helping people. Thanks in advance )
Here is the question and the answer helped me
and here is my function
public static T NvlO<T>(object a, T b)
{
if (a == null)
return b;
else
{
var lSrcType = a.GetType();
var lDestType = typeof(T);
if (lDestType.IsValueType && lDestType.IsAssignableFrom(lSrcType))
return (T)a;
var lDestTC = TypeDescriptor.GetConverter(typeof(T));
if (lDestTC.CanConvertFrom(lSrcType))
return (T)lDestTC.ConvertFrom(a);
else
{
var lSrcTC = TypeDescriptor.GetConverter(lSrcType);
String lTmp = lSrcTC.ConvertToInvariantString(a);
return (T)lDestTC.ConvertFromInvariantString(lTmp);
}
}
}
example of using
long _userID = Utils.NvlO(dr["UserID"], 0);
and if you think that the function does not match the correct programming patterns, write why you think so.