Marcus
Direct CAST vs CType ?
By Marcus in C# on Jul 05 2011
  • Vinoth Arunraj
    Feb, 2012 3

    1) CType is capable of a *cast* or a *conversion*. DirectCast can only
    *cast*

    By "conversion" I mean converting one datatype to another (e.g. string to
    integer, decimal to integer, object to string etc).

    By "cast" I mean changing one type of object into another type that is
    related to it by one of the following rules:

    a) The type you're converting the object to must be the same type
    e.g.
    --------------
    Dim a as String = "hello"
    Dim b as Object = a
    Dim c as string = directcast(b, String)
    --------------

    Variable b is an object that holds a string, so you can cast it to a string.

    b) If converting to an interface, the type you're converting must implement
    the interface
    e.g.
    ---------------------
    Dim a as New MyInterfaceObejct
    Dim b as IInterface = directcast(a, IInterface)
    ----------------------

    c) If converting to a derived type, the runtime type of the object must be
    the derived type or one of it's own derived types :S
    e.g.
    ----------------------
    Dim a as Base = New Derived
    Dim b as Derived = directcast(a, Derived)
    ----------------------

    2) Use directcast whenever a "type relationship" exists - it is slightly
    faster (in some cases anyway), but forces you to be more aware of
    conversions that are going on.

    3) Use Ctype when a type relationship doesn't exist, but a value
    relationship does (e.g. converting the string "123" to the integer 123)

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS