March 28, 2010

Beginners .Net Converting Between Types

Widening Conversion - VB and C# allow implicit converison if destingation type can accomodate all possible values from the source.

For example:
Dim i as Integer = 1
Dim d as Double = 1.0001
d = 1 ' Conversion allowed.

Narrowing Conversion - Range or precision of the source type exceeds the destingation type. Usally requires explicit conversion.

For Example:
.ToString, .TryParse, CBool, Cint, etc.

Boxing - Convert a value type to a reference type.

For Example: Convert Integer to Object
Dim i as Integer = 123
Dim o as Object = CType(i, Object)

UnBoxing - Convert a reference type to a value type.

For Example: Assign reference object to value type.
Dim o as Object = 123
Dim i as Integer = CType(o, Integer)


Use Widening/implicit keyword for conversions that don't lose precision.
Use Narrowing/explicit keyword for conversion that could lose precision.

For Example:
Public Shared Widening Operator CType(ByVal arg as Integer) As TypeA
    Dim res as New TypeA
    res.Value = arg
    Return res
End Operator

MSDN Link:
Extending Design-Time Support How-to and Walkthrough Topics

No comments:

Post a Comment