DirectCast vs CType

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ot

    DirectCast vs CType

    I apparently have a bit to learn about Casting and Conversion. I have been
    thinking of them as the same but a discussion in another thread leads me to
    believe that this is wrong thinking.

    I found this in the VB Language reference:
    <quote>
    The DirectCast keyword introduces a type conversion operation. You use it
    the same way you use the CType keyword....

    Both keywords take an expression to be converted as the first argument, and
    the type to convert it to as the second argument. Both conversions fail if
    there is no conversion defined between the data type of the expression and
    the data type specified as the second argument.
    The difference between the two keywords is that CType succeeds as long as
    there is a valid conversion defined between the expression and the type,
    whereas DirectCast requires the run-time type of an object variable to be
    the same as the specified type. If the specified type and the run-time type
    of the expression are the same, however, the run-time performance of
    DirectCast is better than that of CType.

    DirectCast is special in that conversions from type Object to any other
    type are performed as a direct cast down the hierarchy - all of the special
    conversion behaviors from Object are ignored.

    </quote>

    This last sentence is a bit unclear to me. I am not sure what "special
    conversion behaviors" might be in an Object.

    Further, it says that DirectCast conversions are "performed as a direct
    cast down the hierarchy..." which may be true but is decidedly unhelpful if
    one doesn't know what a "direct cast" is in the first place.

    ----------------------

    "DirectCast requires the run-time type of an object variable to be
    the same as the specified type. If the specified type and the run-time type
    of the expression are the same, however, the run-time performance of
    DirectCast is better than that of CType."

    My interpretation: An object to be DirectCast must already be of the
    desired type. If you know this in advance, DirectCast is faster than
    CType.

    Thanks in advance,
    Ot



  • Ken Tucker [MVP]

    #2
    Re: DirectCast vs CType

    Hi,

    Directcast is faster. See the Conversion Functions, CType,
    DirectCast, and System.Convert section for more info.



    Ken
    -----------------
    "Ot" <uraza@tds.inva lid (use net)> wrote in message
    news:uIYz90L6DH A.2524@TK2MSFTN GP11.phx.gbl...[color=blue]
    >I apparently have a bit to learn about Casting and Conversion. I have been
    > thinking of them as the same but a discussion in another thread leads me
    > to
    > believe that this is wrong thinking.
    >
    > I found this in the VB Language reference:
    > <quote>
    > The DirectCast keyword introduces a type conversion operation. You use it
    > the same way you use the CType keyword....
    >
    > Both keywords take an expression to be converted as the first argument,
    > and
    > the type to convert it to as the second argument. Both conversions fail if
    > there is no conversion defined between the data type of the expression and
    > the data type specified as the second argument.
    > The difference between the two keywords is that CType succeeds as long as
    > there is a valid conversion defined between the expression and the type,
    > whereas DirectCast requires the run-time type of an object variable to be
    > the same as the specified type. If the specified type and the run-time
    > type
    > of the expression are the same, however, the run-time performance of
    > DirectCast is better than that of CType.
    >
    > DirectCast is special in that conversions from type Object to any other
    > type are performed as a direct cast down the hierarchy - all of the
    > special
    > conversion behaviors from Object are ignored.
    >
    > </quote>
    >
    > This last sentence is a bit unclear to me. I am not sure what "special
    > conversion behaviors" might be in an Object.
    >
    > Further, it says that DirectCast conversions are "performed as a direct
    > cast down the hierarchy..." which may be true but is decidedly unhelpful
    > if
    > one doesn't know what a "direct cast" is in the first place.
    >
    > ----------------------
    >
    > "DirectCast requires the run-time type of an object variable to be
    > the same as the specified type. If the specified type and the run-time
    > type
    > of the expression are the same, however, the run-time performance of
    > DirectCast is better than that of CType."
    >
    > My interpretation: An object to be DirectCast must already be of the
    > desired type. If you know this in advance, DirectCast is faster than
    > CType.
    >
    > Thanks in advance,
    > Ot
    >
    >
    >[/color]


    Comment

    • Trev Hunter

      #3
      Re: DirectCast vs CType

      OT,

      Here's a quick outline of the differences and recommendations of where you
      should ctype and directcast (IHMO anyway)

      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 MyInterfaceObej ct
      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)

      The difference has been discussed a lot latley in this group. Have a look at
      the following for more reference:





      HTH,

      Trev.


      Comment

      • Cor

        #4
        Re: DirectCast vs CType

        Hi Ot,

        I thought why am I almost never using CType, and when I saw the answer from
        Trev I knew.

        I use in that kind of situations mostly
        Cdate,
        Cint
        Cdouble
        ..tostring

        In all other situations it is with me
        Directcast (there should be a shortcut on the keyboard for that I think)

        Cor


        Comment

        • Jay B. Harlow [MVP - Outlook]

          #5
          Re: DirectCast vs CType

          Ot,[color=blue]
          > My interpretation: An object to be DirectCast must already be of the
          > desired type. If you know this in advance, DirectCast is faster than
          > CType.[/color]
          In a nut shell that is it!

          DirectCast will only allow the cast if the parameter is already of the
          requested type. Where as CType will find a routine to do a conversion if
          available.

          For example:
          Dim o1 As Object
          Dim o2 As Object
          Dim i As Integer
          o1 = 1 ' o1 contains a boxed Integer
          o2 = "1" ' o2 contains a string

          ' This works as o1 contains an integer
          i = DirectCast(o1, Integer)

          ' This fails as o2 really contains a string
          i = DirectCast(o2, Integer)

          ' this works as there is a conversion from String to Integer
          i = CType(o2, Integer)

          [color=blue]
          > Further, it says that DirectCast conversions are "performed as a direct
          > cast down the hierarchy..." which may be true but is decidedly unhelpful[/color]
          if[color=blue]
          > one doesn't know what a "direct cast" is in the first place.[/color]
          Casting deals with inheritance and what types a variable looks like, it
          looks at both Inherits & Implements keywords. When you use Cast you are
          changing what type the variable looks like, not actually changing what type
          it is. For example System.IO.Strea m: System.IO.Memor yStream inherits from
          Stream so a Memory stream is of type MemoryStream and it is also of type
          Stream. MemoryStream is "down the hierarchy" from Stream, so if you have a
          Stream variable that contains a MemoryStream object, you can use DirectCast
          to look at that variable in its true form a MemoryStream.

          You do understand that when Class1 Inherits from Class2 that Class1 is both
          the Class1 type & the Class2 type? And that when Class1 Implements
          Interface1, that Class1 is both the Class1 type & the Interface1 type? As
          understanding how Inherits & Implements work is needed to understand how
          casting works...

          However in my example above, String does not inherit (or implement) from
          Integer, nor Integer from String, hence the DirectCast does not work, where
          as CType knows there is a routine that will convert (change the type) of
          String into Integer, hence it does work.

          Hope this helps
          Jay


          "Ot" <uraza@tds.inva lid (use net)> wrote in message
          news:uIYz90L6DH A.2524@TK2MSFTN GP11.phx.gbl...[color=blue]
          > I apparently have a bit to learn about Casting and Conversion. I have[/color]
          been[color=blue]
          > thinking of them as the same but a discussion in another thread leads me[/color]
          to[color=blue]
          > believe that this is wrong thinking.
          >
          > I found this in the VB Language reference:
          > <quote>
          > The DirectCast keyword introduces a type conversion operation. You use it
          > the same way you use the CType keyword....
          >
          > Both keywords take an expression to be converted as the first argument,[/color]
          and[color=blue]
          > the type to convert it to as the second argument. Both conversions fail if
          > there is no conversion defined between the data type of the expression and
          > the data type specified as the second argument.
          > The difference between the two keywords is that CType succeeds as long as
          > there is a valid conversion defined between the expression and the type,
          > whereas DirectCast requires the run-time type of an object variable to be
          > the same as the specified type. If the specified type and the run-time[/color]
          type[color=blue]
          > of the expression are the same, however, the run-time performance of
          > DirectCast is better than that of CType.
          >
          > DirectCast is special in that conversions from type Object to any other
          > type are performed as a direct cast down the hierarchy - all of the[/color]
          special[color=blue]
          > conversion behaviors from Object are ignored.
          >
          > </quote>
          >
          > This last sentence is a bit unclear to me. I am not sure what "special
          > conversion behaviors" might be in an Object.
          >
          > Further, it says that DirectCast conversions are "performed as a direct
          > cast down the hierarchy..." which may be true but is decidedly unhelpful[/color]
          if[color=blue]
          > one doesn't know what a "direct cast" is in the first place.
          >
          > ----------------------
          >
          > "DirectCast requires the run-time type of an object variable to be
          > the same as the specified type. If the specified type and the run-time[/color]
          type[color=blue]
          > of the expression are the same, however, the run-time performance of
          > DirectCast is better than that of CType."
          >
          > My interpretation: An object to be DirectCast must already be of the
          > desired type. If you know this in advance, DirectCast is faster than
          > CType.
          >
          > Thanks in advance,
          > Ot
          >
          >
          >[/color]


          Comment

          • Ot

            #6
            Re: DirectCast vs CType

            Thank you all, your responses are appreciated.

            Jay,

            I think I have it....

            Class A

            Class B
            inherits A

            Class C
            inherits B

            Class D
            inherits C

            In that case if I have an object that is an instance of D I could cast it
            to any of A,B,C,D.

            However an object of class C could be cast as A,B or C, but not D.

            If I use, say, a hashtable to store some integers and later get them (they
            are objects when they come back). I could CDbl(o) but not
            DirectCast(o,Lo ng) because the object is really an Integer which is not
            also a Long or Double even though a conversion exists.

            Regards,
            Ot

            "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message
            news:eXzJmFO6DH A.2576@TK2MSFTN GP11.phx.gbl...[color=blue]
            > Ot,[color=green]
            > > My interpretation: An object to be DirectCast must already be of the
            > > desired type. If you know this in advance, DirectCast is faster than
            > > CType.[/color]
            > In a nut shell that is it!
            >
            > DirectCast will only allow the cast if the parameter is already of the
            > requested type. Where as CType will find a routine to do a conversion if
            > available.
            >
            > For example:
            > Dim o1 As Object
            > Dim o2 As Object
            > Dim i As Integer
            > o1 = 1 ' o1 contains a boxed Integer
            > o2 = "1" ' o2 contains a string
            >
            > ' This works as o1 contains an integer
            > i = DirectCast(o1, Integer)
            >
            > ' This fails as o2 really contains a string
            > i = DirectCast(o2, Integer)
            >
            > ' this works as there is a conversion from String to Integer
            > i = CType(o2, Integer)
            >
            >[color=green]
            > > Further, it says that DirectCast conversions are "performed as a direct
            > > cast down the hierarchy..." which may be true but is decidedly[/color][/color]
            unhelpful[color=blue]
            > if[color=green]
            > > one doesn't know what a "direct cast" is in the first place.[/color]
            > Casting deals with inheritance and what types a variable looks like, it
            > looks at both Inherits & Implements keywords. When you use Cast you are
            > changing what type the variable looks like, not actually changing what[/color]
            type[color=blue]
            > it is. For example System.IO.Strea m: System.IO.Memor yStream inherits from
            > Stream so a Memory stream is of type MemoryStream and it is also of type
            > Stream. MemoryStream is "down the hierarchy" from Stream, so if you have[/color]
            a[color=blue]
            > Stream variable that contains a MemoryStream object, you can use[/color]
            DirectCast[color=blue]
            > to look at that variable in its true form a MemoryStream.
            >
            > You do understand that when Class1 Inherits from Class2 that Class1 is[/color]
            both[color=blue]
            > the Class1 type & the Class2 type? And that when Class1 Implements
            > Interface1, that Class1 is both the Class1 type & the Interface1 type? As
            > understanding how Inherits & Implements work is needed to understand how
            > casting works...
            >
            > However in my example above, String does not inherit (or implement) from
            > Integer, nor Integer from String, hence the DirectCast does not work,[/color]
            where[color=blue]
            > as CType knows there is a routine that will convert (change the type) of
            > String into Integer, hence it does work.
            >
            > Hope this helps
            > Jay
            >
            >
            > "Ot" <uraza@tds.inva lid (use net)> wrote in message
            > news:uIYz90L6DH A.2524@TK2MSFTN GP11.phx.gbl...[color=green]
            > > I apparently have a bit to learn about Casting and Conversion. I have[/color]
            > been[color=green]
            > > thinking of them as the same but a discussion in another thread leads[/color][/color]
            me[color=blue]
            > to[color=green]
            > > believe that this is wrong thinking.
            > >
            > > I found this in the VB Language reference:
            > > <quote>
            > > The DirectCast keyword introduces a type conversion operation. You use[/color][/color]
            it[color=blue][color=green]
            > > the same way you use the CType keyword....
            > >
            > > Both keywords take an expression to be converted as the first argument,[/color]
            > and[color=green]
            > > the type to convert it to as the second argument. Both conversions fail[/color][/color]
            if[color=blue][color=green]
            > > there is no conversion defined between the data type of the expression[/color][/color]
            and[color=blue][color=green]
            > > the data type specified as the second argument.
            > > The difference between the two keywords is that CType succeeds as long[/color][/color]
            as[color=blue][color=green]
            > > there is a valid conversion defined between the expression and the[/color][/color]
            type,[color=blue][color=green]
            > > whereas DirectCast requires the run-time type of an object variable to[/color][/color]
            be[color=blue][color=green]
            > > the same as the specified type. If the specified type and the run-time[/color]
            > type[color=green]
            > > of the expression are the same, however, the run-time performance of
            > > DirectCast is better than that of CType.
            > >
            > > DirectCast is special in that conversions from type Object to any other
            > > type are performed as a direct cast down the hierarchy - all of the[/color]
            > special[color=green]
            > > conversion behaviors from Object are ignored.
            > >
            > > </quote>
            > >
            > > This last sentence is a bit unclear to me. I am not sure what "special
            > > conversion behaviors" might be in an Object.
            > >
            > > Further, it says that DirectCast conversions are "performed as a direct
            > > cast down the hierarchy..." which may be true but is decidedly[/color][/color]
            unhelpful[color=blue]
            > if[color=green]
            > > one doesn't know what a "direct cast" is in the first place.
            > >
            > > ----------------------
            > >
            > > "DirectCast requires the run-time type of an object variable to be
            > > the same as the specified type. If the specified type and the run-time[/color]
            > type[color=green]
            > > of the expression are the same, however, the run-time performance of
            > > DirectCast is better than that of CType."
            > >
            > > My interpretation: An object to be DirectCast must already be of the
            > > desired type. If you know this in advance, DirectCast is faster than
            > > CType.
            > >
            > > Thanks in advance,
            > > Ot
            > >
            > >
            > >[/color]
            >
            >[/color]


            Comment

            • Jay B. Harlow [MVP - Outlook]

              #7
              Re: DirectCast vs CType

              Ot,
              Looks like you got it.

              Jay

              "Ot" <uraza@tds.inva lid (use net)> wrote in message
              news:O2o%23l6O6 DHA.2300@TK2MSF TNGP10.phx.gbl. ..[color=blue]
              > Thank you all, your responses are appreciated.
              >
              > Jay,
              >
              > I think I have it....
              >
              > Class A
              >
              > Class B
              > inherits A
              >
              > Class C
              > inherits B
              >
              > Class D
              > inherits C
              >
              > In that case if I have an object that is an instance of D I could cast it
              > to any of A,B,C,D.
              >
              > However an object of class C could be cast as A,B or C, but not D.
              >
              > If I use, say, a hashtable to store some integers and later get them (they
              > are objects when they come back). I could CDbl(o) but not
              > DirectCast(o,Lo ng) because the object is really an Integer which is not
              > also a Long or Double even though a conversion exists.
              >
              > Regards,
              > Ot
              >
              > "Jay B. Harlow [MVP - Outlook]" <Jay_Harlow_MVP @msn.com> wrote in message
              > news:eXzJmFO6DH A.2576@TK2MSFTN GP11.phx.gbl...[color=green]
              > > Ot,[color=darkred]
              > > > My interpretation: An object to be DirectCast must already be of the
              > > > desired type. If you know this in advance, DirectCast is faster than
              > > > CType.[/color]
              > > In a nut shell that is it!
              > >
              > > DirectCast will only allow the cast if the parameter is already of the
              > > requested type. Where as CType will find a routine to do a conversion if
              > > available.
              > >
              > > For example:
              > > Dim o1 As Object
              > > Dim o2 As Object
              > > Dim i As Integer
              > > o1 = 1 ' o1 contains a boxed Integer
              > > o2 = "1" ' o2 contains a string
              > >
              > > ' This works as o1 contains an integer
              > > i = DirectCast(o1, Integer)
              > >
              > > ' This fails as o2 really contains a string
              > > i = DirectCast(o2, Integer)
              > >
              > > ' this works as there is a conversion from String to Integer
              > > i = CType(o2, Integer)
              > >
              > >[color=darkred]
              > > > Further, it says that DirectCast conversions are "performed as a[/color][/color][/color]
              direct[color=blue][color=green][color=darkred]
              > > > cast down the hierarchy..." which may be true but is decidedly[/color][/color]
              > unhelpful[color=green]
              > > if[color=darkred]
              > > > one doesn't know what a "direct cast" is in the first place.[/color]
              > > Casting deals with inheritance and what types a variable looks like, it
              > > looks at both Inherits & Implements keywords. When you use Cast you are
              > > changing what type the variable looks like, not actually changing what[/color]
              > type[color=green]
              > > it is. For example System.IO.Strea m: System.IO.Memor yStream inherits[/color][/color]
              from[color=blue][color=green]
              > > Stream so a Memory stream is of type MemoryStream and it is also of type
              > > Stream. MemoryStream is "down the hierarchy" from Stream, so if you have[/color]
              > a[color=green]
              > > Stream variable that contains a MemoryStream object, you can use[/color]
              > DirectCast[color=green]
              > > to look at that variable in its true form a MemoryStream.
              > >
              > > You do understand that when Class1 Inherits from Class2 that Class1 is[/color]
              > both[color=green]
              > > the Class1 type & the Class2 type? And that when Class1 Implements
              > > Interface1, that Class1 is both the Class1 type & the Interface1 type?[/color][/color]
              As[color=blue][color=green]
              > > understanding how Inherits & Implements work is needed to understand how
              > > casting works...
              > >
              > > However in my example above, String does not inherit (or implement) from
              > > Integer, nor Integer from String, hence the DirectCast does not work,[/color]
              > where[color=green]
              > > as CType knows there is a routine that will convert (change the type) of
              > > String into Integer, hence it does work.
              > >
              > > Hope this helps
              > > Jay
              > >
              > >
              > > "Ot" <uraza@tds.inva lid (use net)> wrote in message
              > > news:uIYz90L6DH A.2524@TK2MSFTN GP11.phx.gbl...[color=darkred]
              > > > I apparently have a bit to learn about Casting and Conversion. I have[/color]
              > > been[color=darkred]
              > > > thinking of them as the same but a discussion in another thread leads[/color][/color]
              > me[color=green]
              > > to[color=darkred]
              > > > believe that this is wrong thinking.
              > > >
              > > > I found this in the VB Language reference:
              > > > <quote>
              > > > The DirectCast keyword introduces a type conversion operation. You use[/color][/color]
              > it[color=green][color=darkred]
              > > > the same way you use the CType keyword....
              > > >
              > > > Both keywords take an expression to be converted as the first[/color][/color][/color]
              argument,[color=blue][color=green]
              > > and[color=darkred]
              > > > the type to convert it to as the second argument. Both conversions[/color][/color][/color]
              fail[color=blue]
              > if[color=green][color=darkred]
              > > > there is no conversion defined between the data type of the expression[/color][/color]
              > and[color=green][color=darkred]
              > > > the data type specified as the second argument.
              > > > The difference between the two keywords is that CType succeeds as long[/color][/color]
              > as[color=green][color=darkred]
              > > > there is a valid conversion defined between the expression and the[/color][/color]
              > type,[color=green][color=darkred]
              > > > whereas DirectCast requires the run-time type of an object variable to[/color][/color]
              > be[color=green][color=darkred]
              > > > the same as the specified type. If the specified type and the run-time[/color]
              > > type[color=darkred]
              > > > of the expression are the same, however, the run-time performance of
              > > > DirectCast is better than that of CType.
              > > >
              > > > DirectCast is special in that conversions from type Object to any[/color][/color][/color]
              other[color=blue][color=green][color=darkred]
              > > > type are performed as a direct cast down the hierarchy - all of the[/color]
              > > special[color=darkred]
              > > > conversion behaviors from Object are ignored.
              > > >
              > > > </quote>
              > > >
              > > > This last sentence is a bit unclear to me. I am not sure what[/color][/color][/color]
              "special[color=blue][color=green][color=darkred]
              > > > conversion behaviors" might be in an Object.
              > > >
              > > > Further, it says that DirectCast conversions are "performed as a[/color][/color][/color]
              direct[color=blue][color=green][color=darkred]
              > > > cast down the hierarchy..." which may be true but is decidedly[/color][/color]
              > unhelpful[color=green]
              > > if[color=darkred]
              > > > one doesn't know what a "direct cast" is in the first place.
              > > >
              > > > ----------------------
              > > >
              > > > "DirectCast requires the run-time type of an object variable to be
              > > > the same as the specified type. If the specified type and the run-time[/color]
              > > type[color=darkred]
              > > > of the expression are the same, however, the run-time performance of
              > > > DirectCast is better than that of CType."
              > > >
              > > > My interpretation: An object to be DirectCast must already be of the
              > > > desired type. If you know this in advance, DirectCast is faster than
              > > > CType.
              > > >
              > > > Thanks in advance,
              > > > Ot
              > > >
              > > >
              > > >[/color]
              > >
              > >[/color]
              >
              >[/color]


              Comment

              Working...