0
0
CsharpConceptBeginner · 3 min read

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.

csharp
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
    }
}
Output
Alice
🎯

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 get or set.
  • Using properties improves code safety and readability.

Key Takeaways

Properties use get and set to control reading and writing data safely.
get returns the current value; set assigns a new value with optional checks.
Use properties to protect private data and add rules for changing values.
Properties make your code easier to maintain and understand.