Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use get and set properties in C#

Tags:

c#

When should we use get and set properties in C#?

like image 872
user544079 Avatar asked Mar 16 '11 06:03

user544079


People also ask

Why we use get and set with properties?

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.

What is the use of Get and set?

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.

Why do we use get and set properties in C#?

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.

Why use get set instead of public?

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.


1 Answers

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.

like image 76
Cody Avatar answered Oct 05 '22 02:10

Cody