Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
A mutator, in the context of C#, is a method, with a public level of accessibility, used to modify and control the value of a private member variable of a class. The mutator is used to assign a new value to the private field of a type. It forms a tool to implement encapsulation by only controlling access to the internal field values that must be modified.
The benefits of using a mutator include:
A mutator is usually provided with an accessor that returns the value of the member variable. For data members that are immutable, the mutator should not be provided.
For example, StudentData can be a class that stores a student's details, such as name, address, grade, etc. There can be a public method, SetGrade in the class. StudentData is the mutator to update the StudentData object from the code that uses the object.
While a mutator is implemented in C++ by an explicit public method to modify a private field, C# introduces "properties" as a new feature that implements a mutator to modify field values as well as an accessor to fetch the field. Each property is represented in the common intermediate language code with a pair of methods prefixed with "get_"(accessor) and "set_"(mutator) under the hood. They are called internally by the common language runtime (CLR). This simplifies the code and sometimes allows for the performance of mathematical operations.
The mutator is not often used in objects, where the object's behavior is considered rather than how it performs.