In object-oriented programming, encapsulation is a fundamental concept that involves bundling the data (attributes) and methods (functions) that operate on the data into a single unit or class. Encapsulation also restricts direct access to some of an object's components, which can prevent the accidental modification of data. In C#, properties provide a way to encapsulate fields by allowing you to define methods that are called when a field is accessed or modified.
A property in C# is a member that provides a flexible mechanism for reading, writing, or computing the value of a private field. Properties can include both a getter and a setter method, which control how the data is accessed and modified. This allows you to add logic to enforce validation rules, perform additional actions when a value changes, or compute values dynamically.
Let's explore some practical examples to understand how properties work in C#.
Here is a simple example of a class with a property:
1public class Person2{3private string name;45public string Name6{7get { return name; }8set { name = value; }9}1011public void DisplayName()12{13Console.WriteLine("Name: " + name);14}15}1617class Program18{19static void Main(string[] args)20{21Person person = new Person();22person.Name = "Alice";23person.DisplayName(); // Output: Name: Alice2425Console.WriteLine("Accessing property directly: " + person.Name); // Output: Accessing property directly: Alice26}27}
In this example, the Name property encapsulates the private field name. The getter and setter methods allow you to access and modify the value of name.
You can add validation logic in the setter method to ensure that only valid data is assigned:
1public class Person2{3private string name;45public string Name6{7get { return name; }8set9{10if (string.IsNullOrEmpty(value))11{12throw new ArgumentException("Name cannot be null or empty.");13}14name = value;15}16}1718public void DisplayName()19{20Console.WriteLine("Name: " + name);21}22}2324class Program25{26static void Main(string[] args)27{28Person person = new Person();29try30{31person.Name = ""; // This will throw an exception32}33catch (ArgumentException ex)34{35Console.WriteLine(ex.Message); // Output: Name cannot be null or empty.36}37}38}
In this example, the setter method checks if the value is null or empty and throws an exception if it is. This ensures that the name field always contains a valid string.
A read-only property has only a getter method:
1public class Circle2{3private double radius;45public Circle(double radius)6{7this.radius = radius;8}910public double Radius11{12get { return radius; }13}1415public double Area16{17get { return Math.PI * radius * radius; }18}19}2021class Program22{23static void Main(string[] args)24{25Circle circle = new Circle(5);26Console.WriteLine("Radius: " + circle.Radius); // Output: Radius: 527Console.WriteLine("Area: " + circle.Area); // Output: Area: 78.5398163397448328}29}
In this example, the Radius property is read-only, meaning it can only be set during object initialization. The Area property is a computed property that returns the area of the circle based on its radius.
A write-only property has only a setter method:
1public class Logger2{3private string logFile;45public string LogFile6{7set { logFile = value; }8}910public void WriteLog(string message)11{12File.AppendAllText(logFile, message + Environment.NewLine);13}14}1516class Program17{18static void Main(string[] args)19{20Logger logger = new Logger();21logger.LogFile = "log.txt";22logger.WriteLog("This is a log message.");23}24}
In this example, the LogFile property is write-only, meaning it can only be set after object initialization. The WriteLog method writes messages to the specified log file.
Now that you have learned about properties in C#, you should explore how they contribute to encapsulation and data validation. In the next section, we will dive into indexers in C#, which provide a way to access elements of a collection using an indexer syntax similar to arrays.
Stay tuned for more tutorials on object-oriented programming in C#!