Properties in C# Programming


Introduction

In C#, properties provide a way to access and modify the values of private fields. They serve as an interface between the private fields of a class and the outside world. Properties are a type-safe way to encapsulate data, making it easier to add validation or logic when getting or setting a value.

This tutorial will cover:

  • Getters and setters
  • Auto-implemented properties

Getters and Setters

A property in C# consists of two main components:

  • Getter: A method that retrieves the value of a private field.
  • Setter: A method that assigns a value to a private field.

Getters and setters provide controlled access to the private fields, allowing additional logic, validation, or processing when getting or setting a value.

Syntax for Getters and Setters

    public type PropertyName
    {
        get
        {
            // Return the value of the private field
            return privateField;
        }
        set
        {
            // Assign a value to the private field
            privateField = value;
        }
    }
        

Example: Using Getters and Setters

Let’s define a Person class with a private field name, and a property to access and set it. We'll also add logic to the setter to validate the name before assigning it.

    using System;     class Person
    {
        private string name;         // Property with getter and setter
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    name = value;
                }
                else
                {
                    Console.WriteLine("Name cannot be empty");
                }
            }
        }
    }     class Program
    {
        static void Main()
        {
            Person person = new Person();             // Setting the name using the setter
            person.Name = "Alice";             // Getting the name using the getter
            Console.WriteLine("Name: " + person.Name);             // Attempt to set an invalid name
            person.Name = "";  // Output: Name cannot be empty
        }
    }
        

Output:

    Name: Alice
    Name cannot be empty
        

Auto-Implemented Properties

In C#, auto-implemented properties provide a shorthand way of creating properties without needing to explicitly define a private field for storing the value. The compiler automatically creates a private, anonymous backing field to store the value of the property.

Auto-implemented properties are convenient when you don't need to add custom logic to the getter or setter.

Syntax for Auto-Implemented Properties

    public type PropertyName { get; set; }
        

Example: Using Auto-Implemented Properties

Let’s define a Book class with an auto-implemented property Title.

    using System;     class Book
    {
        // Auto-implemented property
        public string Title { get; set; }
    }     class Program
    {
        static void Main()
        {
            Book book = new Book();             // Setting the title using the auto-implemented property
            book.Title = "The C# Programming Guide";             // Getting the title using the auto-implemented property
            Console.WriteLine("Book Title: " + book.Title);
        }
    }
        

Output:

    Book Title: The C# Programming Guide
        

Read-Only and Write-Only Properties

In some cases, you may want to allow only getting or setting the value of a property. You can make a property read-only or write-only by defining either the getter or setter only.

Read-Only Property

A read-only property only has a getter and cannot be assigned a value outside the class.

Example: Read-Only Property

    using System;     class Person
    {
        private string name;         // Read-only property
        public string Name
        {
            get { return name; }
        }         // Constructor to initialize the name
        public Person(string name)
        {
            this.name = name;
        }
    }     class Program
    {
        static void Main()
        {
            Person person = new Person("Bob");             // Getting the name using the getter
            Console.WriteLine("Name: " + person.Name);             // The following will cause an error because the property is read-only:
            // person.Name = "Alice";  // Error: Cannot assign to 'Name' because it is read-only
        }
    }
        

Output:

    Name: Bob
        

Write-Only Property

A write-only property only has a setter and cannot be read from outside the class.

Example: Write-Only Property

    using System;     class Person
    {
        private string name;         // Write-only property
        public string Name
        {
            set { name = value; }
        }
    }     class Program
    {
        static void Main()
        {
            Person person = new Person();             // Setting the name using the setter
            person.Name = "Charlie";             // The following will cause an error because the property is write-only:
            // Console.WriteLine(person.Name);  // Error: 'Name' is write-only
        }
    }
        

Conclusion

In this tutorial, we've learned about properties in C#, including:

  • Getters and setters for controlling access to private fields and adding custom logic.
  • Auto-implemented properties for simplifying property declaration when no additional logic is required.
  • Read-only and write-only properties for controlling whether a property can be read or written to.

Understanding properties is essential for managing data and encapsulating logic within your classes in C#. By using properties effectively, you can ensure that your code is clean, readable, and secure.




Advertisement