I have a class that exposes an auto implemented property Enabled
Public MustInherit Class TopLevel
Protected Property Enabled() As Boolean
End Class
In an inhertited class I cannot access _Enabled
Public Class SubClass
Inherits TopLevel
Public Function Foo() As string
If Not _Enabled Then Return Nothing '<- This fails
End SUb
End Class
But If I had not use an auto implemented property and declared my own backing-field as follows this is accessible from the subclass:
Private _Enabled as Boolean
—- EDIT —-
The abve line is incorrect – this is not possible, it was in fact Protected in the original code which allowed access from the sub class See @JonSkeet answer
—- EDIT —-
Of course I can just access Enabled from the sub class to work around this but can someone explain why this is the behaviour?
No it wouldn’t – private fields aren’t accessible from derived classes – only protected ones are. (The exception to this being nested classes, which have access to their containing class’s private members.)
From the docs for the Private modifier:
Personally I’d regard it as bad form to access the backing field of an automatically implemented property directly anyway – in C#, it’s not even available, as it’s given an unspeakable name (one which isn’t valid in C# itself). If you want the value of the property from your derived class, why don’t you just access it as a property? That would be the appropriate approach even if you weren’t using automatically implemented properties – your fields should be private.