This is a search subject I’ve done quite a few times in the past and never really found a good answer. I’ve found results either asking the same question and debate/bicker threads about the obsolete-ness of CInt, but none that describe the difference between the two. Plenty of “if you try to convert X using Y, Z will happen if you don’t W X first” that don’t give an explanation.
A recent epiphany finally lifted the veil on the question’s answer: Convert.ToInt32 (and the rest of the .ToX methods in the Convert class) is a method – CInt (and its relatives) are type-casting directives (similar to the C# syntax (int)x; or (string)y;).
The prime difference is the Convert class’ .ToX methods perform additional logic (as methods are wont to do) before employing a type-casting directive and returning the result. Disassembling Convert.ToByte in the .NET Framework library “mscorlib.dll” with Red Gate .NET Reflector supplies the evidence:
Public Shared Function ToByte(ByVal value As Integer) As Byte If ((value < 0) OrElse (value > &HFF)) Then Throw New OverflowException(Environment.GetResourceString("Overflow_Byte")) End If Return CByte(value) End Function
This is the VB.NET representation of mscorlib’s IL for the method; if you disassemble this method into C#, the last line of the method reads: (byte)value;
The Convert class’ conversion methods employ a type-casting mechanism as they return their result. They also throw exceptions when the conversion could presumably be invalid. The difference here is that if you use direct type-casting (CInt, etc.) you may or may not get an exception when an employing them on an invalid argument.
I say “may or may not”, because the default setting for throwing Overflow/Underflow exceptions is different for VB.NET projects versus C# projects. In VB.NET libraries the default is to throw an exception when an overflow would occur and C# libraries default to the converse – in C# if you try to cast the integer value “10000″ to a byte the result will be 0 and code execution will continue.
The following truth counters the argument/rumor that “VB.NET’s CInt and its siblings are obsolete”: CInt is shorthand for “CType(
Why write “CType(someVariable, Integer)” when you can write “CInt(someVariable)” and save 10 keystrokes (35%). What a deal!.