1. Herfried K. Wagner’s VB.Any
  2. .NET
  3. Häufig gestellte Fragen

Warum ist MyBase.MyBase nicht möglich?

Warum ist 'MyBase.MyBase' nicht möglich?

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'
grandbase could lead to inconsistencies in an object's state.  The sample
below illustrates such a case:

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)
        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 grandbase class directly, bypassing a base function, where the base
function is needed for the entire hierarchy to function correctly.