I don't know what the correct wording is for what I am trying to achieve so it may already be posted online. Please be kind if it is.
Ok so basically I have this method.
public static T IsNull<T>(IDataReader dr, String name, T nullValue)
{
return Helpers.IsNull(dr, dr.GetOrdinal(name), nullValue);
}
public static T IsNull<T>(IDataReader dr, Int32 index, T nullValue)
{
if (dr.IsDBNull(index))
{
return nullValue;
}
else
{
return (T)dr.GetValue(index);
}
}
Being called as Helpers.IsNull(dr, "UnitWholeSale", 0d)
and the error I am getting is "Cannot convert from double to decimal".
Now I know I can use decimal.Zero
but is there some way that I can simply go 0dec or something similar? I just hate those long shortcut values (especially when you are calling a constructor with 20 parameters).
Be aware that each last example is a cast and therefor can lose precision
M
is the suffix fordecimal
values, e.g.200.32M
is considered to be of typedecimal
to the compiler.0m
will give you adecimal
0 value.For the sake of completeness,
I assume
nullValue
is reallydefaultvalue
, otherwise you could just doAlso looking more closely at your method you probably want a convertible value and use
Convert.ChangeType()
, I don't think the simple casting would work for all types:Use
0.0m
instead -m
denotesdecimal
.0m
is how you say(decimal)0
becausem
is the suffix that meansdecimal
.Other suffixes are
f
forfloat
,d
fordouble
,u
forunsigned
, andl
forlong
. They can be either upper- or lower-case andu
can be combined withl
in either order to make aulong
.Although the suffixes are not case-sensitive, keep in mind what it says in the C# language specification, section 2.4.4.2: