I have a base class with several derived classes. I want all of my derived classes to have the same Public Shared
(static) method with their own implementation. How do I do this? Is it even possible?
views:
57answers:
3No. You could use a singleton, but there may be a better design.
By definition, a static method cannot be declared as virtual. To achieve this without static methods you would do something like the following:
public abstract class BaseFoo
{
protected virtual void Bar()
{
}
}
public class Foo : BaseFoo
{
protected override void Bar()
{
base.Bar();
}
}
If you wanted to achieve something similar to having it as static you could use the singleton pattern so that you share a single instance of the object.
Edit:
I realized your original question talked about VB syntax, so here's the same thing in VB:
Public MustInherit Class BaseFoo
Protected Overridable Sub Bar()
End Sub
End Class
Public Class Foo
Inherits BaseFoo
Protected Overrides Sub Bar()
MyBase.Bar()
End Sub
End Class
I know this seems like a useful feature "at design time" but imagine how this could be used:
If GetForms
is Shared
(static
in C#) you don't have an object with a type to distinguish which method to use, i.e. you can't say BaseForm.GetForms()
in some way that it can be determined which of ChildFormTypeA.GetForms()
and ChildFormTypeB.GetForms()
is actually called.
The best you can do is document this is the intention if you just want explicit calls to ChildFormTypeA.GetForms()
and ChildFormTypeB.GetForms()
, or if you really need the concept make it a factory method e.g.
MustInherit Class BaseForm
MustOverride Sub GetForms()
End Class
Class MyForm
Inherits BaseForm
Public Sub New()
End Sub
Overrides Sub GetForms()
End Sub
End Class
Now you just need
Dim f as BaseForm = New MyForm
f.GetForms
Alternatively GetForms
might be Protected
and called from the Sub New
.