2

I knew VB.net is very weird when talking about shadows and overloads, but this this I'm completely baffled.

I'm working with a model similar to the following one. Parent class:

Public Class Base
    Function F() As String
        Return "F() in Base Class"
    End Function

    Function F(ByVal n As Integer) As String
        Return "F(" + n.ToString() + ") in Base Class"
    End Function
End Class

and this:

Class Derived
    Inherits Base
    Shadows Function F() As String
        Return "-"
    End Function
End Class

when running the following:

Sub Main()
    Dim parent As Base = New Base()
    Dim child As Derived = New Derived()

    Console.WriteLine(parent.F())
    Console.WriteLine(parent.F(1))
    Console.WriteLine("------------")

    Console.WriteLine(child.F())
    Console.WriteLine(child.F(1)) 'this should not compile, due to the shadow keyword.

    Console.Read()
End Sub

an IndexOutOfRangeException is thrown. Moreover, when changing (in derived Class): Return "-" for Return "Func in derived class" console prints character 'u'. Does somebody knows the reason for this?

mbmihura
  • 542
  • 1
  • 8
  • 13

3 Answers3

5

Your F is a string, so when you specify the index, it is looking at the index of the string, not the second function with the integer parameter.

"u" is the second character in "Func", specified by index 1.

For your example, you would have to shadow the second function, too:

Class Derived
  Inherits Base

  Shadows Function F() As String
    Return "-"
  End Function

  Shadows Function F(ByVal n As Integer) As String
    Return "X"
  End Function
End Class
LarsTech
  • 80,625
  • 14
  • 153
  • 225
3

Your code is indexing a String rather than calling a function with a parameter.

Console.WriteLine(child.F(1))

This line is expanded to:

Dim childFResult As String = child.F()
Dim character As Char = F.Chars(1) ' Failure here.
Console.WriteLine(character)

Because String.Chars is the default property, you can reference it by index alone. Your string only contains one character, so there is no character at index 1.

Hand-E-Food
  • 12,368
  • 8
  • 45
  • 80
3

It is a syntax ambiguity in vb.net, () can mean both 'method call' and 'array index'. You got the array index version, index 1 is out of bounds for the string returned by F(). Or in other words, the compiler compiles this:

Console.WriteLine(child.F(1)) 

to this:

Dim temp1 As String = child.F()
Dim temp2 As Char = temp1(1)
Console.WriteLine(temp2)

The second statement causes the exception. C'est la vie.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536