Why Is MyBase.MyBase
Not Allowed?
In Visual Basic .NET, C#, and Java access is resticted to the direct base class. The main reason for this is that allowing access to a class’ grand-base could lead to inconsistencies in an object’s state. The sample below illustrates this problem:
Public Class A
Private m_Sum As Integer
Public Overridable Sub Add(ByVal Number As Integer)
m_Sum += Number
End Sub
End Class
Public Class B
Inherits A
Private m_Checksum As Integer
Public Overrides Sub Add(ByVal Number As Integer)
MyBase.Add(Number)
m_Checksum = …
End Sub
End Class
Public Class C
Inherits B
' Objects of type 'C' are objects of type 'B' too. 'B' guarantees that the
' checksum will be set properly. If there was a way to call ' 'A''s 'Add'
' method directly, the checksum set in 'B' would not be updated and thus the
' class' state would be inconsistent.
End Class
MyBase.MyBase
could be used to bypass code that is required by the class hierarchy, for example, if the derived class calls a function defined in its grand-base class directly, bypassing a base function, where the base function is needed for the entire class hierarchy to work correctly.