Paste and convert

What is the difference between Cast and Convert in C # 2008?

+2


source to share


3 answers


Cast will allow you to safely convert certain types of data, for example. double-> int

double a = 3.5;
int b = (int) a; //fraction will be truncated

      

Here, cast takes a 3.5 binary representation and puts it in an integer representation. Since the integer has no fractions, it is discarded and resolved as well. Allocating a string to an integer this way is not that easy and not allowed by the compiler.



Converting is smarter and converting more data types from one to another, for example. string -> boolean

string myString = "true";
bool myBool = Convert.ToBoolean(myString);

      

Also see the discussion of this discussion on stack in this section.

+3


source


One difference: Convert methods allow you to specify specific formatting (e.g. IFormatProvider)



0


source


Casting is generally slower and can perform explicit and explicit conversion operations

-1


source







All Articles