BuddyJoe
BuddyJoe

Reputation: 71101

VB.NET and OOP - Shared Methods and Base Properties

If you can't use Me. in a non-instance method, how would you use properties/functions from a base class in a Shared method?

For example, ClassB inherits from ClassA
ClassB has a Shared Method DoWork(); ClassA has a ReadOnly Property SecurityKey

How do I …

Public Sub DoWork()
  Dim test as String = Me.SecurityKey 
End Sub  

Upvotes: 1

Views: 4049

Answers (5)

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

Dim s as SecKey = ClassA.SecurityKey

This pulls from a shared method. Remember that shared methods are shared by all instances of a class, so you use the class name to pull them.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415765

Using your examples:

Which ClassA instance should the shared ClassB.DoWork() get when it tries to reference the Me.SecurityKey property?

If you make the ClassA.SecurityKey property also shared that would make a little more sense, but then the inheritance relationship is no longer important. You might just as well say ClassA.SecurityKey inside that method, because you would have to already know about ClassA to know about it's inherited property anyway.

If you make ClassB.DoWork() as an instance method rather than a shared method, you can use the MyBase keyword in VB.Net to reference the inherited ClassA property, even if ClassB overloads or shadows it.

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

If you can't use "Me." in a non-instance method, how would you use properties/functions from a base class in a Shared method?

You can't. Shared methods (and static in C#) don't work well together with OOP. This (i.e. the fact that static/shared methods cannot be virtual/overridable) is arguably a design flaw in the .NET system that was “inherited” from Java. Shared methods aren't actually object methods, rather they are global methods with a name scope.

Additionally, and perhaps even more related to your problem, you always need an instance to access a non-shared method (which, being shared, does not belong to any particular instance).

Upvotes: 3

Quintin Robinson
Quintin Robinson

Reputation: 82335

You access shared members by the classname and not an instance identifier.. IE: ClassA.DoWork() You cannot access instance members from shared methods/members because they are different scope. However you can access shared members from instance scope without using the instance identifier.

Try passing an instance of the class to your method or instantiating the class in the shared method.

Public Shared Sub DoWork(instance As ClassB)
    Dim test As String = instance.WhateverProperty;
End Sub

Upvotes: 2

baretta
baretta

Reputation: 7595

If you're in a static context, you would need to instantiate this class to access its instance members.

Upvotes: 0

Related Questions