What is Properties Get and Set with Example Code

In C#, properties provide a way to encapsulate fields by exposing them through methods.They allow controlled access to the fields of a class, enabling validation, computation,or other processing when getting or setting their values. Properties are declared using the get and set accessors.




using System;

// Define a class named Person

class Person

{

    // Private fields

    private string name;

    private int age;

 

    // Constructor

    public Person(string name, int age)

    {

        this.name = name;

        this.age = age;

    }

 

    // Property with get and set accessors for the Name field

    public string Name

    {

        get { return name; }

        set { name = value; } // 'value' represents the value being assigned to the property

    }

 

    // Property with get and set accessors for the Age field

    public int Age

    {

        get { return age; }

        set

        {

            if (value >= 0 && value <= 60) // Validate age to be within a reasonable range

            {

                age = value;

            }

            else

            {

                Console.WriteLine("Invalid age. Age must be between 0 and 120.");

            }

        }

    }

}

 

class Program

{

    static void Main(string[] args)

    {

        // Create a Person object

        Person person = new Person("A", 28);

        // Get and set properties

        Console.WriteLine($"Initial Name: {person.Name}, Age: {person.Age}");

        person.Name = "A"; // Set Name property

        person.Age = 28; // Set Age property

        Console.WriteLine($"Updated Name: {person.Name}, Age: {person.Age}");

        // Try setting an invalid age

        person.Age = 60; // This will trigger the validation in the Age property setter

    }

}