What is get and set in C#: Simple Explanation and Example
get and set are special parts of a C# property that control reading and writing a value. get returns the value, while set assigns a new value, allowing controlled access to private data.How It Works
Think of a property in C# like a mailbox for a house. The get part is like opening the mailbox to take out mail (reading the value), and the set part is like putting mail into the mailbox (writing the value). This lets you control how people see or change the information inside.
Behind the scenes, properties use private variables to store data safely. The get method returns the current value of this variable, and the set method updates it. This way, you can add rules or checks when someone tries to change the value, like making sure a number is positive.
Example
This example shows a simple class with a property that uses get and set to control access to a private field.
public class Person { private string name; // private field public string Name { get { return name; } // read access set { name = value; } // write access } } class Program { static void Main() { Person person = new Person(); person.Name = "Alice"; // calls set System.Console.WriteLine(person.Name); // calls get } }
When to Use
Use get and set when you want to control how a class's data is accessed or changed. This helps keep data safe and consistent.
For example, you might want to prevent setting a negative age or automatically update related values when a property changes. Properties with get and set let you add these rules easily.
They are also useful to hide the internal details of a class, so users only interact with the property, not the private data directly.
Key Points
- get returns the property value.
- set assigns a new value to the property.
- Properties provide controlled access to private fields.
- You can add validation or logic inside
getorset. - Using properties improves code safety and readability.