Question Class protected variable get set

Bubb

Member
Joined
Jan 28, 2020
Messages
5
Programming Experience
Beginner
Hi, so I'm just playing with some properties and struggling with this concept of Auto-Implemented Properties
Example

protected int health { get; set; }

Where usually I would make a private health and making a public method with a get/set below. I'm unclear how to access the protected get/set via main? Or do I still need to make another method to access / change this protected variable?

Thank you in advance
 
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
So you use the property directly also internally in class.
 
Article I linked to has example.
 
A protected member is accessible within its class and by derived class instances.
This almost the same as private field; private is only accessible within its class.
 
A property is not a variable. Properties is the external interface for internal state that is stored in private fields (class variables). Maybe protected isn't the right modifier for you? Of course the property can be protected if it is supposed to only be accessible is derived classes, but if you meant it to be accessible to other classes then you must declare it public or internal.
If you don't intend this storage to be accessible outside the class then it should not be written as a property, but instead as a private field.
 
Last edited:
Back
Top Bottom