8.26.2012

Difference between Implicit Conversion and Explicit Conversion

Difference between Implicit Conversion and Explicit Conversion
S.No Implicit Conversion Explicit Conversion
1 Implicit Conversion perform automatically in VB.NET, that is the compiler is taking care of the conversion and therefore does not require any special syntax in the source code. In some cases we have to perform conversions , that is the compiler does not automatically convert a type to another . These type of conversion is called Explicit conversion . An explicit conversion uses a type conversion keyword, eg.CType ,CInt ,CStr etc., With these conversion keywords we have to perform the Explicit Conversion

Example for Implicit Conversion:

Dim K As Integer
Dim Q As Double
' ...
K = 432 ' Integer widens to Double, so Option Strict can be On.
Q = K

In the above example, Visual Basic .NET implicitly converts the value of K to single-precision floating point before assigning it to Q.

Example for Explicit Conversion:

Dim K As Integer
Dim Q As Double
' ...
K = 432 ' Integer widens to Double, so Option Strict can be On.
Q = K

Q = Math.Sqrt(Q) ' Q had been assigned the value 432 from K.
K = CInt(Q) ' K now has the value 21 (rounded square root of 432).

In the above example, the CInt keyword converts the value of Q back to an integer before it is assigned to K

No comments:

Post a Comment