Question Using Virtual On Procedure

phicha

Well-known member
Joined
May 11, 2009
Messages
45
Programming Experience
Beginner
How to using virtual on sub class method to calling base class method ?


thanks,
 
Your question is a bit difficult to understand. I'll provide an answer to what I think the question is but if I'm wrong then you're going have to try to rephrase the question.

I think you're asking how to override a method in a derived class and then call the base implementation. If so then the base class might look like this:
VB.NET:
Public Class TheBaseClass

    Public Overridable Sub SomeMethod()
        'Do something here.
    End Sub

End Class
and the derived class might look like this:
VB.NET:
Public Class TheDerivedClass
    Inherits TheBaseClass

    Public Overrides Sub SomeMethod()
        'Do pre-processing here if required.

        'Call the base implementation.
        MyBase.SomeMethod()

        'Do post-processing here if required.
    End Sub

End Class
Note that "virtual" is a C term and is used in C# but not in VB. In VB it's "Overridable".
 
ya its exactly what i need
thanks sir,

just wonder if we called mybase.somemethod than will it excuted the method from based.


and i have others question more, if there is a interface, implemented to a class and struct. and on the struct and class there is method from implement interface. and there is a method that passing a parameter interface.

how can i execute those parameter that work on struct and class ?

thanks a lot,
 
I'm not sure what you're asking but, again, I'll have a go based on what I think you mean. If you have this interface:
VB.NET:
Public Interface IGreeting
    Sub SayHello(ByVal name As String)
End Interface
and these types that implement that interface:
VB.NET:
Public Class EnglishGreeting
    Implements IGreeting

    Public Sub SayHello(ByVal name As String) Implements IGreeting.Greet
        MessageBox.Show("Hello " & name)
    End Sub

End Class


Public Structure FrenchGeeting
    Implements IGreeting

    Private dummy As Object

    Public Sub SayBonjour(ByVal name As String) Implements IGreeting.Greet
        MessageBox.Show("Bonjour " & name)
    End Sub

End Structure
and this method that has a parameter of that interface type:
VB.NET:
Public Sub DisplayGeeting(ByVal greeting As IGreeting, ByVal name As String)
    greeting.Greet(name)
End Sub
Then you can pass any object that implements the IGreeting interface to the DisplayGreeting method, e.g.
VB.NET:
Dim eg As New EnglishGreeting
Dim fg As New FrenchGeeting

DisplayGeeting(eg, "John")
DisplayGeeting(fg, "John")
Note that the methods that implement the Greet method of the interface don't have to be called Greet, although if they don't you then can't call Greet on an EnglishGreeting or FrenchGreeting object. You must cast them as type IGreeting first to call Greet. It's generally good practice to use the same name unless you have a specific reason not to.
 
Last edited:
Back
Top