What are the accessors?
In the context of C# programming and object-oriented concepts, accessors refer to the methods used to control the accessibility of the fields (variables) within a class. Accessors allow you to define how these fields can be read from or written to from outside the class.
There are two main types of accessors: getters and setters.
1.
Getter (Accessor): A getter is a method that provides read access to the value of a field. It's used to retrieve the value of a field from outside the class. In C#, getters are defined using the 'get' keyword. Getters typically return the value of the associated field.
class MyClass
{
private int myNumber;
public int MyNumber
{
get { return myNumber; } // Getter
}
}
2.
Setter (Accessor): A setter is a method that provides write access to the value of a field. It's used to assign a value to a field from outside the class. In C#, setters are defined using the 'set' keyword. Setters typically accept a value parameter and assign it to the associated field.
class MyClass
{
private int myNumber;
public int MyNumber
{
get { return myNumber; }
set { myNumber = value; } // Setter
}
}
In many cases, you'll find that accessors are used in conjunction with properties. Properties provide a convenient way to encapsulate fields and define the rules for reading and writing those fields. They allow you to expose fields while maintaining control over how they are accessed and modified.
class Temperature
{
private double celsius;
public double Celsius
{
get { return celsius; } // Getter
set { celsius = value; } // Setter
}
public double Fahrenheit
{
get { return celsius * 9 / 5 + 32; } // Computed property without a setter
}
}
In the above example, the 'Celsius' property has both a getter and a setter, while the 'Fahrenheit' property only has a getter, as its value is computed based on the 'Celsius' property.
Accessors play a crucial role in encapsulation and data hiding, allowing you to control how external code interacts with the internal state of your classes.