Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Cast and Convert in C#

Tags:

c#

decimal

I have a sql datareader...From which I have to fetch one decimal value.

What is the difference between

  1. (decimal)datareader["percent"]

and

  1. Convert.Todecimal(datareader["percent"])

And what are prons and cos ....of both methods.

like image 784
Relativity Avatar asked Dec 05 '22 00:12

Relativity


2 Answers

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
like image 53
cdhowie Avatar answered Dec 07 '22 13:12

cdhowie


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.

like image 25
J.D. Avatar answered Dec 07 '22 14:12

J.D.