When should we use get and set properties in C#?
It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.
The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.
A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.
The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly.
Properties are probably what you're looking for if you decide you need get and set methods. For a decent discussion as to why you would, and why you wouldn't want to use properties check out Jon Skeet's Why Properties Matter.
One good reason for using properties as opposed to just exposing internal class data is obviously to protect that data. You can control access for individual attributes as well as validate data that is being set. You can also implement calculated properties to calculate values, this will appear no different than any other attribute to a user of your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With