none
Funny little pop quiz RRS feed

  • Question

  •  

    You have to use VB to do this, but I thought it was quite fun, can you guess what this does?

     

    Dim bla As Object = CDate("2001-12-11")

    Console.WriteLine(bla.ToString("yyyy-MM-dd"))

     

     

     

    ......

     

    Did you guess it?.....

     

     

    {"Conversion from string "yyyy-MM-dd" to type 'Integer' is not valid."}

     

     

    (Sorry if it's obvious but it suprised me).

     

     

     

     

    Monday, May 19, 2008 3:40 PM

Answers

  • It is probably caused by a leak in the VB.NET syntax.  Parentheses can both be used for a method call and to index an array or string.  And parentheses are optional if the method doesn't take any arguments.  That's a lethal combination in this case.  The compiler parses it as follows:

            Dim v As Object = CDate("2001-12-11")
            Dim s As String = v.ToString
            Dim i As Integer = CInt("yyyy-mm-dd")
            Dim t As String = s(i)
            Console.WriteLine(t)

    It is the CInt() call that generates the exception.  Still sounds like a compiler bug, the Console.WriteLine() method is required.  You can report it at the Connect web site.
    Tuesday, May 20, 2008 8:44 PM
    Moderator

All replies

  • The Object class doesn't have a ToString(String) overload.  Put Option Strict On at the top of your source code file to catch these kind of mistakes early.  Still a crummy error message though.
    Tuesday, May 20, 2008 12:11 AM
    Moderator
  • Yes option strict sort it out, but the odd thing is why it complains about a cast to int, the code it generates is...

    obj.ToString()("yyyy-mm-dd")

    i.e. it sees the ToString as a argument-less call followed by the indexer into the returning string, just a bit wierd.

    Tuesday, May 20, 2008 8:04 PM
  • It is probably caused by a leak in the VB.NET syntax.  Parentheses can both be used for a method call and to index an array or string.  And parentheses are optional if the method doesn't take any arguments.  That's a lethal combination in this case.  The compiler parses it as follows:

            Dim v As Object = CDate("2001-12-11")
            Dim s As String = v.ToString
            Dim i As Integer = CInt("yyyy-mm-dd")
            Dim t As String = s(i)
            Console.WriteLine(t)

    It is the CInt() call that generates the exception.  Still sounds like a compiler bug, the Console.WriteLine() method is required.  You can report it at the Connect web site.
    Tuesday, May 20, 2008 8:44 PM
    Moderator