vb.net After Contruction trigger

The VB implementation of auto properties of this form:

Public Overrides ReadOnly Property x As Integer = 9

Defers assignment to the underlying variable until after the base class constructor has been called. You can verify this by setting some breakpoints strategically. This behavior is not obvious from the syntax of the child constructor, which misleadingly implies that the child class is initialized before MyBase.New is called.

If you use the following form instead, it will always return 9:

Public Overrides ReadOnly Property x As Integer
        Return 9
    End Get
End Property

If this isn’t suitable due to details that you omitted as part of simplifying the question, you can use an Overridable or MustOverride routine to ensure that this setup has already occurred during the base class constructor (as Hursey suggested).

As an aside: It’s interesting to contemplate whether it would make sense to change this behavior at the language level. My best guess is that the current behavior is to avoid problems with trying to have a property depend on anything from the base class when the base class might not be fully initialized yet. It would be safe to have an exception for compile-time constants (constexpr in C++ lingo), but that could introduce confusing inconsistency with non-constant values; I think the current behavior is the most correct in the general sense assuming that the child-class property initialization might depend on things requiring base-class initialization.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top