0
0
C Sharp (C#)programming~5 mins

Get and set accessors in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Get and set accessors let you read and change values inside an object safely.

When you want to control how a value is read or changed in a class.
When you want to check or change data before saving it.
When you want to hide the details of how data is stored.
When you want to make some values read-only or write-only.
When you want to add extra actions when a value changes.
Syntax
C Sharp (C#)
public class ClassName
{
    private DataType fieldName;

    public DataType PropertyName
    {
        get { return fieldName; }
        set { fieldName = value; }
    }
}

get returns the value.

set assigns a new value using the keyword value.

Examples
This example shows a simple property Name that gets and sets a private field name.
C Sharp (C#)
public class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}
This example adds a check in set to only allow non-negative ages.
C Sharp (C#)
public class Person
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            if (value >= 0) age = value;
        }
    }
}
This is a short way to create a property without writing a field.
C Sharp (C#)
public class Person
{
    public string Name { get; set; } // Auto-implemented property
}
Sample Program

This program creates a Person object and sets the age. It shows how the set accessor blocks negative values and prints a message.

C Sharp (C#)
using System;

public class Person
{
    private int age;

    public int Age
    {
        get { return age; }
        set
        {
            if (value >= 0) age = value;
            else Console.WriteLine("Age cannot be negative.");
        }
    }
}

class Program
{
    static void Main()
    {
        Person p = new Person();
        p.Age = 25;
        Console.WriteLine($"Age: {p.Age}");

        p.Age = -5; // This should show a warning
        Console.WriteLine($"Age after invalid set: {p.Age}");
    }
}
OutputSuccess
Important Notes

You can make a property read-only by only providing a get accessor.

Use value inside set to get the new value being assigned.

Auto-implemented properties are quick but you cannot add extra logic inside get or set.

Summary

Get and set accessors let you control how values are read and changed in a class.

You can add checks or extra actions inside get or set.

Auto-properties provide a quick way to create simple properties without extra code.