I have two classes, one that inherits from the other. The base class is MustInherit/abstract and defines a MustOverride/abstract property.
As part of the base classes initialization, it sets a variable based on the value of the abstract property. The problem is that the inheriting class accepts as its parameter the value which should be assigned to the overriden property. The inherited class sets this property, but not before calling the base class’ initializer.
Basically, I need to initialize part of the base class, then allow the inheriting class to initialize some of its properties, then return to the base class to finish initializing more properties.
I would make the property part of the base class, but the inheriting classes employ strong typing whereas the base class only needs an interface.
Code example:
MustInherit Class A
MustOverride Property X As IExample
Sub New()
' Do some stuff
_privateY = X.Foo() ' NullReferenceException
End Sub
End Class
Class B
Inherits A
Override Property X As IExample ' returns StrongX
Property StrongX As ConcreteExample ' ConcreteExample implements IExample
Sub New(x As ConcreteExample)
MyBase.New(x)
StrongX = x
End Sub
End Class
It is exactly for this reason that abstract members should not be called in the constructor. http://msdn.microsoft.com/en-us/library/ms182331(v=vs.100).aspx
If you have control of the abstract class I would suggest passing the value in through the base class constructor.