Best, absolutely the best practice is no casting at all! In many cases, it's possible to design code without type cases. Use generics, in particular.
However, in some cases, type casting is unavoidable. Sometimes even dynamic casting using "
as
" is needed, but this is often a sign of OOP abuse. You did not ask about it, but it's important to know:
http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=VS.100%29.aspx[
^].
See also
http://msdn.microsoft.com/en-us/library/scekt9xw.aspx[
^].
As to "
Convert
", to me, this is often a sign of lack of understanding (even when it works correctly). A cast is not conversion, a conversion is not a cast. A "classic" cast like (int)… is better, but not always applicable. In your case, it is probably not. If the input is string, it's much better to use
Parse
or
TryParse
, as it reflects the essence of what's actually done.
The cast like (int)… is mostly uses to cast downcasting (
http://en.wikipedia.org/wiki/Downcasting[
^], note the danger of it) and casting to a narrower type like int to short, int to byte, etc. In all cases, casting can fail, should be used with care. More exactly, it should be uses mostly when you can know in advance that the case is successful.
—SA