I have a sql datareader...From which I have to fetch one decimal value.
What is the difference between
and
And what are prons and cos ....of both methods.
Casting will succeed only if the object returned by datareader["percent"]
is of the type Decimal
. Conversion will succeed when the object is of any type convertible to Decimal
. This includes int
, long
, short
, etc. Or more generally, anything that implements IConvertible
and returns a useful value from IConvertible.ToDecimal()
can be passed to Convert.ToDecimal()
.
For example:
csharp> object a = (int)1;
csharp> a.GetType();
System.Int32
csharp> var dec = (decimal)a;
System.InvalidCastException: Cannot cast from source type to destination type.
at Class3.Host (System.Object& $retval) [0x00000] in <filename unknown>:0
at Mono.CSharp.Evaluator.Evaluate (System.String input, System.Object& result, System.Boolean& result_set) [0x00000] in <filename unknown>:0
at Mono.CSharpShell.Evaluate (System.String input) [0x00000] in <filename unknown>:0
csharp> var dec = Convert.ToDecimal(a);
csharp> dec;
1
csharp> dec.GetType();
System.Decimal
I don't know about decimal specifically, but I know that for integers Convert rounds whereas casting truncates, i.e. (int)7.6 is 7, Convert.ToInt32(7.6) is 8. Not directly applicable to your example, but good to keep in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With