ingredient_15939
ingredient_15939

Reputation: 3134

The equivalent of c# virtual in vb when calling method *within* base class

I understand how to use VB's Overridable and Overrides, to get similar functionality to c#'s virtual when calling methods of a class. However, consider the c# console code below, which calls an overridden method from within the class itself:

class Program {
  static void Main(string[] args) {
    new test();
    new test2();
    Console.ReadKey();
  }
}

public class test {
  public test() {
    hello();
  }
  public virtual void hello() {
    Console.WriteLine("hello from base method");
  }
}

class test2 : test {
  public override void hello() {
    Console.WriteLine("hello from overridden method");
  }
}

The result I get, predictably, in c# is:

hello from base method
hello from overridden method

The problem is, I can't work out how to duplicate this functionality in VB.NET. Keep in mind here that hello() is being called from within the base class code, which runs the overridden method. That is what I can't seem to accomplish in VB.

No matter what I try in VB, the base class's hello() is always called, not the overridden hello().

Upvotes: 1

Views: 6314

Answers (1)

Nostromo
Nostromo

Reputation: 1264

Class Test:

Public Class Test

    Public Sub New()
        Hello()
    End Sub

    Public Overridable Sub Hello()
        Console.WriteLine("hello from base method")
    End Sub

End Class

Class Test2:

Public Class Test2
    Inherits Test

    Public Overrides Sub Hello()
        Console.WriteLine("hello from overridden method")
    End Sub

End Class

Sub Main:

Sub Main()
    Dim x As New Test
    Dim y As New Test2
End Sub

Upvotes: 3

Related Questions