Getters And Setters

Lesson 28
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In object-oriented programming, getters and setters are methods that allow us to access and modify the values of private instance variables in a class. They are also known as accessors and mutators, respectively.

A private instance variable is a variable that is declared inside a class and is only accessible within that class. This is done to prevent other parts of the program from accidentally modifying the variable’s value. However, we still need a way to read and modify the variable’s value within the class itself.

That’s where getters and setters come in. A getter is a method that returns the value of a private instance variable, while a setter is a method that sets the value of a private instance variable.

Here’s an example of a class with private instance variables and getter/setter methods in C#:

public class Person
{
    private string name;
    private int age;

    public string GetName()
    {
        return name;
    }

    public void SetName(string newName)
    {
        name = newName;
    }

    public int GetAge()
    {
        return age;
    }

    public void SetAge(int newAge)
    {
        age = newAge;
    }
}

In this example, we have a class called Person with two private instance variables: name and age. We also have four methods that allow us to get and set these variables: GetName(), SetName(), GetAge(), and SetAge().

The GetName() method returns the value of the name variable, while the SetName() method sets the value of the name variable to the value passed in as an argument. Similarly, the GetAge() method returns the value of the age variable, while the SetAge() method sets the value of the age variable to the value passed in as an argument.

Using getter/setter methods allows us to control access to the private instance variables in our classes. We can add additional logic to these methods to validate input or perform other actions whenever the values of these variables are accessed or modified.