Which of the following code is fastest/best practice for converting some object x?
int myInt = (int)x;
or
int myInt = Convert.T
Fastest != Best Practice!
For example, (int)
is almost certainly the fastest because it's an operator rather than a function call, but it will only work in certain situations.
The best practice is to use the most readable code that won't negatively impact your performance, and 99 times out of 100 an integer conversion isn't driving your app's performance. If it is, use the most appropriate, narrowest conversion you can. Sometimes that's (int)
. Sometimes it's TryParse()
. Sometimes it's Convert.ToInt32()
.