Whats the difference between Cast & Convert in C# 2008?
Asked
Active
Viewed 1,200 times
2
-
This question is very very vague. In which context? Are you talking about conversion operators? – nawfal Nov 29 '13 at 12:01
-
possible duplicate of [is-casting-the-same-thing-as-converting](http://stackoverflow.com/questions/143997/is-casting-the-same-thing-as-converting) – nawfal Jul 12 '14 at 16:12
3 Answers
3
Cast will allow you to convert certain data types safely, eg. double-> int
double a = 3.5;
int b = (int) a; //fraction will be truncated
Here cast is taking the binary representation of 3.5 and putting it into integer representation. Because integer doesn't have fractions it is dropped and also allowed. Casting a string to an integer in this way is not so simple and not allowed by the compiler.
Convert is smarter and convert more data types from one to another, eg. string -> boolean
string myString = "true";
bool myBool = Convert.ToBoolean(myString);

Community
- 1
- 1

Philip Fourie
- 111,587
- 10
- 63
- 83
0
One difference is Convert methods allow specific formatting (ie. IFormatProvider)

Inisheer
- 20,376
- 9
- 50
- 82
-1
Cast is generally slower, and can do implict and explicit converion operators

waqasahmed
- 3,555
- 6
- 32
- 52
-
4I would be interested to know why you claim that cast is slower? Have look at the implementation of Convert.ToInt32(double value). It ends up doing a cast internally and additional operations. – Philip Fourie Aug 30 '09 at 04:47