I have 2 classes A
and B
, which share 2 functions S1
and S2
consisting of absolutely identical code in both classes:
Public Class A
Private Coll as New Collection
Public Sub A1()
End Sub
Public Function A2() As String
End Function
'Identical functions:
Public Function S1() As Int32
...
Coll.Add(Something1)
End Function
Public Function S2() As Boolean
...
Coll.Add(Something2)
End Function
End Class
Public Class B
Private Coll as New Collection
Public Sub B1(Arg1 As Boolean)
End Sub
Public Function B2() As Int32
End Function
'Identical functions:
Public Function S1() As Int32
...
Coll.Add(Something1)
End Function
Public Function S2() As Boolean
...
Coll.Add(Something2)
End Function
End Class
S1
and S2
are factory functions interacting with instance fields and producing some objects, which go into local collections in A
and B
, respectively, hence solutions with Shared
are likely no option (?), nor seem packing the common functions into a base class feasible (?).
For maintanability reasons, I'd like to have the whole code block containing S1
and S2
defined in just one place, ideally in a dedicated file "CommonMethods.vb"
.
For usability reasons, I need access to all members directly, without using an intermediate class C
. The presence of C
would be absolutely anti-intuitive whatever it's named. Intellisense should display the following members when typing A.
A1, A2, S1, S2
and not
A1, A2, C
and when typing B.
B1, B2, S1, S2
and not
B1, B2, C
If #Include Filename
existed in VB.NET, I would do:
Public Class A
Public Sub A1()
End Sub
Public Function A2() As String
End Function
#Include CommonFunctions.vb
End Class
Public Class B
Public Sub B1(Arg1 As Boolean)
End Sub
Public Function B2() As Int32
End Function
#Include CommonFunctions.vb
End Class
but there is no #Include
.
Hence the question: how can I share identical code text?
You can place all the common functionality - fields, properties, methods, etc. - in the base class and declare it Protected
if you want it accessible to the base class and derived classes but not to consumers of those classes. In cases where the implementations might be different between base classes, you can always declare the base class and those members MustInherit
and MustOverride
respectively.