tags:

views:

221

answers:

5

I have a class that inherits from a base class (this contains a lot of common db related stuff amongst other things and is marked as MustInherit). I want to write a shared methodin which I call a base class method, however the compiler gives me the message 'MyBase is only valid within an instance method'. This shared method is a logging method and will be used a lot within the app, I'm trying to avoid having to instantiate an object each time I want to call it.

Is it possible to access the base class methods from a shared method?

+3  A: 

No, as the compiler states you cannot call an instance method from a shared method.

Since an instance of a class is separate from any other instance each call to a method on that instance can potentially create different results and side-effects as an instance method has access to the instance's state. A shared method does not have access to the state of any instance since the shared method is shared between all instance of the type.

Since this is the case it is impossible to call an instance method from a shared method because a shared method is "instance-less".

Andrew Hare
A: 

You may want to look at using the Registry Pattern.

Patrick McDonald
+1  A: 

Well since a shared method does not have state, calling a instance method is not possible in the sence you a re thinking, but dont dispair there is always a shared instantiated instance at the field level that your shared method can reference, in your case maby a private class that inherits from your base

something like

Public Class Foo
private Shared ReadOnly Instance as New Somthing

Public Shared Function DooFoo as string
   return instance.Getstring()
End Function

Private class Something : inherits baseclass
   public function Getstring() as string
    ....
   End function 
End Class



End Class
almog.ori
That is not completely true - a shared method does not have access to instance state but it does have access to shared state (shared fields for instance).
Andrew Hare
Yes thats what Ive done here, its a shared field
almog.ori
I agree I just mean that your wording is a bit unclear as shared state *is* state but it is the state of the *type* rather than any instance of that type.
Andrew Hare
Yes I agree with your comment too, this is just a solution to the problem of creating an instance over and over, and where something inherits from the base class in question.
almog.ori
A: 

Is the method you want to access in the base class a shared method? If so, just make the method protected, and in your sub class, call it without the MyBase keyword.

Jules
+1  A: 

You actually don't need to, since you cannot have shared overridable methods in VB. You just need to specify base class like this:

Class B

    Public Shared Sub Foo()
      ' code
    End Sub

End Class

Class D : Inherits B

    Public Shared Sub Bar()
        B.Foo() ' calls base class method
    End Sub

End Class
catbert