array conversions

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

    array conversions

    Why does the following code throw an exception?

    Dim o1() As Object = New Object() {"Sankar", "Sankar2"}
    s = DirectCast(o1, String())

    Following is a snippet from VB.NET language specification on MSDN.


  • Cor Ligthert

    #2
    Re: array conversions

    Sankar,

    Is the sample not this
    Dim s() As String
    Dim o1() As Object = _
    New String() {"Sankar", "Sankar2"}
    s = DirectCast(o1, String())

    In my opinion are you trying to cast some arrays containing different
    objects.
    Not one object to a given type.

    I hope this helps?

    Cor


    Comment

    • Cor Ligthert

      #3
      Re: array conversions

      Sankar,

      Is the sample not this
      Dim s() As String
      Dim o1() As Object = _
      New String() {"Sankar", "Sankar2"}
      s = DirectCast(o1, String())

      In my opinion are you trying to cast some arrays containing different
      objects.
      Not one object to a given type.

      I hope this helps?

      Cor


      Comment

      • Herfried K. Wagner [MVP]

        #4
        Re: array conversions

        "Sankar Nemani" <snemani@nospam lumedx.com> schrieb:[color=blue]
        > Why does the following code throw an exception?
        >
        > Dim o1() As Object = New Object() {"Sankar", "Sankar2"}
        > s = DirectCast(o1, String())[/color]


        This won't work. You'll have to cast each item in the array individually.

        \\\
        Dim o1() As Object = {"Sankar", "Sankar2"}
        Dim s1(o1.Length - 1) As String
        For i As Integer = 0 To o1.Length - 1
        s1(i) = DirectCast(o1(i ), String)
        Next i
        ///

        --
        M S Herfried K. Wagner
        M V P <URL:http://dotnet.mvps.org/>
        V B <URL:http://dotnet.mvps.org/dotnet/faqs/>


        Comment

        • Herfried K. Wagner [MVP]

          #5
          Re: array conversions

          "Sankar Nemani" <snemani@nospam lumedx.com> schrieb:[color=blue]
          > Why does the following code throw an exception?
          >
          > Dim o1() As Object = New Object() {"Sankar", "Sankar2"}
          > s = DirectCast(o1, String())[/color]


          This won't work. You'll have to cast each item in the array individually.

          \\\
          Dim o1() As Object = {"Sankar", "Sankar2"}
          Dim s1(o1.Length - 1) As String
          For i As Integer = 0 To o1.Length - 1
          s1(i) = DirectCast(o1(i ), String)
          Next i
          ///

          --
          M S Herfried K. Wagner
          M V P <URL:http://dotnet.mvps.org/>
          V B <URL:http://dotnet.mvps.org/dotnet/faqs/>


          Comment

          Working...