Getters and Setters in C#

Everything has particular qualities that allow us to distinguish it from others. In C# programming, we similarly use the theory of property. If you've ever heard of encapsulation, you'll know that we try to hide private data or information from particular users during the encapsulation process. During encapsulation, we frequently apply the public getter and setter functions to access and modify certain private field values through the property notion. As a result, we will go over how to use getter and setter functions in C# programs to achieve encapsulation at various inheritance levels.

What exactly are Getters and Setters?

Getters, as well as setters, are just functions with a similar name in a class. The getter provides the value of a private field variable, whereas the setter adjusts its importance. These methods verify that a class's private information (fields) is accessed and modified securely and accurately.

What is their purpose?

Consider using a public class automobile with a private strings descriptive property name. If someone from outside the class wants to receive the description, they can only if it's private. The getters and setters are useful in this situation.

A getter might enable users to obtain the value of private string descriptions without granting them direct access to edit it. Conversely, a setter would allow users to edit the implicit parameter descriptions within the criteria we define.

What are Access Modifiers?

Access Modifiers: A field or property's accessibility and visibility from outside of the class are defined by access modifiers. Public and private are the most often used modifiers.

Public: Declared public fields or properties can be retrieved anywhere in your program. For example, you may provide a public int salary property that any section of your code can view and modify.

Private properties or fields:  Private properties or fields, such as private int salary, are accessible only within the defined class. This encapsulation prevents unauthorized modifications and guarantees that the class's internal state is properly maintained.

Getter and Setter Functions

Let's start with an easy example.

using System;


class Employee


{


    private string name;


    public string GetName()


    {


        return name;


    }


    public void SetName(string newName)


    {


        name = newName;


    }


}


class Program


{


    static void Main(string[] args)


    {


        Employee employee = new Employee();


        employee.SetName("Amini");


        string employeeName = employee.GetName();


        Console.WriteLine(employeeName); // This will print "Amini"


    }


}

Output:

Getters and Setters in C#

The name property in the referenced class Employee has two getters (GetName) and a setter (SetName). Whenever you call the static void Main method, it will print "Amini" because we used the setter to set that value for the name.

Auto-Implementation Features

Should the getter and setter methods be written separately? The short response is "no." This is made easier by the concept of "auto-implemented properties" in C#, referred to as "automatic properties."

Automatic properties in C# provide a shortcut for defining a private field and its related property. Here's an example:

using System; // Add this using a directive at the beginning of your code


public class Student


{


    public string Name { get; set; }


}


class Program


{


    static void Main(string[] args)


    {


        Student student = new Student();


        student.Name = "Ganesh"; // Setting the Name property


        string studentName = student.Name; // Getting the Name property


        Console.WriteLine(studentName); // This will print "Ganesh"


    }


}

Output:

Getters and Setters in C#

The Name property in the Student class has both a getter and a setter that is auto-implemented. Behind the scenes, the C# compiler constructs a private string name field accessible via the Name property.

Access modifiers properties

You can manage the visibility and accessibility of properties, as well as the getters and setters that go with them, across all of your classes and the rest of your codebase by using access modifiers in C#. They assist you in deciding on the level of data protection and encapsulation you desire for your properties.

Here are the commonly used access modifiers:

Public: Properties with a public access modifier are accessible from any part of your code, including external classes and assemblies. Both the getter and setter are public.

public int MyProperty { get; set; }

Example usage:

MyClass myObject = new MyClass();


int value = myObject.MyProperty;  // Accessible from anywhere


myObject.MyProperty = 42;         // Accessible from anywhere

Private Setter with Public Getter: This approach creates read-only properties accessible from any part of your code, but only the class containing the property can modify its value.

public int MyReadOnlyProperty { get; private set; }

Example usage:

MyClass myObject = new MyClass();


int value = myObject.MyReadOnlyProperty;  // Accessible from anywhere


// myObject.MyReadOnlyProperty = 42;      // Cannot modify outside the class

Protected: Properties with a protected access modifier can only be accessed and modified within the declaring class or its derived classes.

protected int MyProtectedProperty { get; set; }

Example usage:

class MyDerivedClass : MyBaseClass


{


    public void SomeMethod()


    {


        int value = MyProtectedProperty;  // Accessible within derived class


        MyProtectedProperty = 42;         // Accessible within derived class


    }


}


Internal: Properties marked as internal are accessible from any class within the same assembly (project).


internal int MyInternalProperty { get; set; }

Example usage:

// In the same assembly


MyClass myObject = new MyClass();


int value = myObject.MyInternalProperty;  // Accessible within the assembly


myObject.MyInternalProperty = 42;         // Accessible within the assembly

Protected Internal: Combining protected and internal properties with this modifier are accessible within the same assembly and also by derived classes in other assemblies.

protected internal int MyProtectedInternalProperty { get; set; }

Example usage:

// In the same assembly


MyClass myObject = new MyClass();


int value = myObject.MyProtectedInternalProperty;  // Accessible within the assembly


myObject.MyProtectedInternalProperty = 42;         // Accessible within the assembly


// In a derived class from another assembly


MyDerivedClass derivedObject = new MyDerivedClass();


int derivedValue = derivedObject.MyProtectedInternalProperty;  // Accessible in the derived class


derivedObject.MyProtectedInternalProperty = 42;               // Accessible in derived class

Private Protected: Properties marked as private protected are accessible within the same assembly and by derived classes in other assemblies. However, they are not accessible from external code.

private protected int MyPrivateProtectedProperty { get; set; }

Example usage:

// In the same assembly


MyClass myObject = new MyClass();


int value = myObject.MyPrivateProtectedProperty;  // Accessible within the assembly


myObject.MyPrivateProtectedProperty = 42;         // Accessible within the assembly


// In a derived class from another assembly


MyDerivedClass derivedObject = new MyDerivedClass();


int derivedValue = derivedObject.MyPrivateProtectedProperty;  // Accessible in a derived class


derivedObject.MyPrivateProtectedProperty = 42;               // Accessible in derived class


// Attempting to access from external code will result in an error

Readonly Field (Immutable): Fields marked as readonly can only be assigned a value once, typically in the constructor of the class that declares them. They cannot be modified afterward.

public readonly int MyReadOnlyField = 42;


Example usage:


MyClass myObject = new MyClass();


int value = myObject.MyReadOnlyField;  // Accessible from anywhere


// myObject.MyReadOnlyField = 42;      // Cannot modify after initialization

These access modifiers are essential for maintaining the integrity of your code and controlling how data is accessed and modified in different parts of your application.

The Iron Suite: Improve Your C# Development

The Iron Suite is a group of tools for research that vastly improves C# programming skills. IronPDF, IronXL, IronOCR, and IronBarcode are among its components. Each of these tools has a special function and can be merged into other C# features.

Powerful PDF Management Tool: IronPDF

Developers may create, read, and edit PDF files in C# using the IronPDF package. IronPDF has you covered for everything from controlling PDF metadata with getters and setters to converting HTML to PDF using the HTML to PDF guide.

Excel Manipulation Made Simple With IronXL

IronXL makes reading and writing Excel files easier. This tool may be used to manipulate the private and public strings or numbers in Excel files, much like how you would deal with data inside a class through the same syntax of getters and setters in C#.

IronOCR is an optical character recognition library written in C#.

IronOCR is an OCR library that converts photos into searchable text. IronOCR's robust features can be readily integrated if your application requires text reading from scanned documents. It is capable of handling private fields as well as public string descriptions.

IronBarcode is a library for reading and writing barcodes.

IronBarcode is a must-have application for anyone who needs to read and write barcodes. It supports direct accessibility to barcode data and customization using automated properties, similar to how getters and setters are implemented in C# programming.

Getters and Setters, as well as the Iron Suite

The Iron Suite package integrates neatly with C# programming, including getters and setters. These tools improve the quality of any C# project.

Conclusion:

Accessing and modifying a class's private fields is made easier with getter and setter functions.

Automatically implemented properties are a stylish method to have automatic getters and setters.

A property's accessibility can be adjusted with the aid of access modifiers.

The use of getters and setters in C# should be something you understand quite well by this point.