tags:

views:

472

answers:

3
+3  Q: 

MyClass in VB.Net

What is a realistic use for VB.Net's MyClass keyword?

I understand the technical usage of MyClass; I don't understand the practical usage of it in the real world.

Using MyClass only makes sense if you have any virtual (overridable) members. But it also means that you want to ignore the overridden implementations in sub classes. It appears to be self-contradicting.

I can think of some contrived examples, but they are simply bad design rather than practical usage.

A: 

I guess the only case I could see a use for it, would be if you want the base condition, and an inherited condition at the same time? I.E. where you want to be able to inherit a member, but you want the ability to access a value for that member that hasn't been changed by inheritance?

KiwiBastard
then why allow that member to be overridden in the first place?
Robert Taylor
+1  A: 

Polymorphism

I'm sorry I don't have a clear code example here but you can follow the link below for that and I hate to copy the MSDN Library description but it's so good that it's really hard to rewrite it any clearer.

"MyClass provides a way to refer to the current class instance members without them being replaced by any derived class overrides. The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented."

Also note that you can't use MyClass in a shared method.

A good example of implementing Polymorphism via MyClass is at http://www.devarticles.com/c/a/VB.Net/Implementing-Polymorphism-in-VB.Net/

Adam Caviness
You quoted "MyClass provides a way to refer to the current class instance members without them being replaced by any derived class overrides."Then why mark your members as overrideable in the first place?
Robert Taylor
A: 

You need it if you want to call a chained constructor.

Public Sub New(ByVal accountKey As Integer)
    MyClass.New(accountKey, Nothing)
End Sub

Public Sub New(ByVal accountKey As Integer, ByVal accountName As String)
    MyClass.New(accountKey, accountName, Nothing)
End Sub

Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String)
    m_AccountKey = accountKey
    m_AccountName = accountName
    m_AccountNumber = accountNumber
End Sub
Jonathan Allen
Nope; Me.New(...) or MyBase.New(...) will work just fine.
Robert Taylor