In C#, properties provide a way to encapsulate private fields and provide controlled access to their values. They are a type of class member that is used to expose the state of an object while hiding its implementation details.
A property consists of a getter and/or setter method that is used to read or modify the value of a private field. The syntax for declaring a property in C# is:
access-modifier type PropertyName
{
get { /* getter logic */ }
set { /* setter logic */ }
}
Here’s an example of a class with a property:
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
In this example, we have a private field called “name” and a public property called “Name”. The property provides controlled access to the “name” field by allowing the value to be read and set through its getter and setter methods.
We can access the property like this:
Person person = new Person();
person.Name = "John Doe"; // Setter is called
Console.WriteLine(person.Name); // Getter is called
In this example, we set the value of the “Name” property to “John Doe” using its setter method. Then we retrieve the value using the getter method and output it to the console.
By using properties, we can maintain the integrity of our object’s state by controlling how it is read and modified. We can also add additional logic to the getter and setter methods, such as validation or error handling, to ensure that the values are correct and consistent.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.