Difference between Cast and Convert in C #

I have a datareader sql ... from which I should get one decimal value.

What's the difference between

  • (decimal) DataReader ["percent"]

and

  • Convert.Todecimal (DataReader ["percent"])

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

+4
source share
5 answers

Casting will succeed only if the object returned by datareader["percent"] is of type Decimal . The conversion will succeed if the object is of any type convertible to Decimal . This includes int , long , short , etc. Or, in general, anything that implements IConvertible and returns a usable value from IConvertible.ToDecimal() can be passed to Convert.ToDecimal() .

For instance:

 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 
+11
source

I do not know about the decimal value, but I know that for integers the conversion is rounds, while the casting is truncation, i.e. (int) 7.6 equals 7, Convert.ToInt32 (7.6) - 8. Not applicable directly to your example, but useful to keep in mind.

+3
source

EDIT

Casting says the object is of type (or derivative). Convert says that although it may not be the same type or derivative, there is a way to access the destination type.

eg.

 string a = "1234"; object b = a; // success, a is really a string string c = (string)b; // fails because b is not actually an int int d = (int)b; // success because there is way to convert the numeric string to an int int e = Convert.ToInt32(b); 

EDIT: Good point @cdhowie, Freudian miss. This should be a little more visual.

0
source

The first ( (decimal)datareader["percent"] ) is an explicit cast. What he does is that he forces the compiler to unpack or pass the target value ( datareader["percent"] ) to decimal . This will InvalidCastException unless the datareader["percent"] is decimal or in the decimal box.

The second is the startup code, which is part of .NET, which checks which datareader["percent"] object is and tries to convert it to decimal accordingly. This will succeed if the value is any number (e.g. int ).

0
source

Some good answers here, but since you mentioned SqlDataReader, you have the GetDecimal () method instead of using the indexer syntax ["columnName"]. I don't know if it will buy you any performance, but it gives you type safety without using Convert or casting.

0
source

Source: https://habr.com/ru/post/1332707/


All Articles