C# Properties

In C#, properties represent a unique class element designed to offer a streamlined approach for accessing, modifying, and calculating the value of a private field. They serve as an enhancement of fields, accessible in a similar manner. Properties serve as a conduit connecting fields and methods, enabling regulated interaction with class data.

The <style> element includes a CSS class for a placeholder diagram. This class sets the background color using a linear gradient, adds rounded corners, sets padding and margins, and aligns the content in the center. Additionally, it includes a sub-class for the placeholder icon, which determines the size and spacing of the icon, and a sub-class for the placeholder text, which defines the color and font size of the text within the placeholder diagram.

Properties are frequently employed in object-oriented programming (OOP) as they facilitate encapsulation and abstraction. Accessors associated with properties are utilized to assign, retrieve, or calculate their values. These accessors do not store any data themselves.

Why use Properties in C#?

There are several uses of C# properties. Some of them are as follows:

  • C# Properties can have read-only or write-only access.
  • Properties can protect class member fields using encapsulation, which is used to hide the implementation details.
  • These can be used to access private data members of the class from another using accessors.
  • These are used to protect class members so that another class cannot use these members.
  • These properties are used to enhance the code readability and maintainability.
  • Syntax:

It has the following syntax:

Example

class Class_Name

{

    private datatype field_Name;  // Private field

    public datatype Property_Name

    {

        get {return field_Name;}   // using Getter method

        set {field_Name = value;}  // using Setter method

    }

}

In this syntax,

  • Class_Name: It represents the name of the Class.
  • get: It is only used to access (read) the property value.
  • set: It is used to assign (write-only) the new value to the property.
  • value: It is used to hold the value that is assigned by the user.
  • Simple Example of Properties

Let's consider an example to demonstrate the characteristics in C#.

Example

Example

using System;

class Employee

{

    private string name;   // using Private field

    // using Property

    public string Name

    {

        get { return name; }

        set { name = value; }

    }

}

class C# Tutorial

{

    static void Main()

    {

        Employee emp = new Employee();

        emp.Name = "Michael";         // Using property setter

        Console.WriteLine(emp.Name); // Using property getter

    }

}

Output:

Output

Michael

Explanation:

In this instance, we are utilizing a property called Name to manage access to the private field name. Subsequently, we are employing the set accessor to set the value to "Michael", while the get accessor is utilized to fetch this value.

Accessor in C#

In C#, within a property, an accessor is a code block that defines the behavior of how the property interacts with a private field of a class. Accessors play a crucial role in enforcing encapsulation by managing the external read and write operations on class fields. They guarantee the security of internal data and control the access to it.

Types of Accessors

In C#, there are primarily two categories of accessors. These are outlined below:

The CSS code snippet below defines the styling for a placeholder diagram. This diagram includes a background with a linear gradient, a border with rounded corners, padding, margin spacing, and center alignment for the content. The placeholder icon within the diagram is set to a specific font size with some margin at the bottom. Additionally, the placeholder text is styled with a particular color and font size.

Here, we will discuss these accessors one by one.

1) Get Accessor

In C# programming, the get accessor retrieves the value of a private field. This is beneficial when we need different parts of the program to access the value without the ability to modify it.

C# Get Accessor Example

Let's consider an example to illustrate the get accessor in C#.

Example

Example

using System;

class Employee

{

    private int employeeId;

    public Employee(int id)

    {

        employeeId = id;

    }

    public int EmployeeId

    {

        get

        {

            return employeeId;

        }

    }

}

class C# Tutorial

{

    static void Main()

    {

        Employee emp = new Employee(101);

        Console.WriteLine("The Employee ID is: " + emp.EmployeeId);

    }

}

Output:

Output

The Employee ID is: 101

Explanation:

In this instance, a property named EmployeeId is defined to provide read-only access to the private field employeeId, ensuring it cannot be modified externally. Subsequently, the constructor sets the field to the value 101, and the get accessor retrieves and displays it.

2) Set Accessor

In C#, a set accessor establishes a value for a private field. This method is invoked each time a value is assigned to a property. The keyword "value" is employed within the set block to symbolize the data being passed in.

C# Set Accessor Example

Let's consider an example to illustrate the set accessor in C#.

Example

Example

using System;

class User

{

    private string password;

    public string Password

    {

        set

        {

            password = value;

        }

    }

    public void ShowMaskedPassword()

    {

        Console.WriteLine("Password is set (hidden for security).");

    }

}

class Program

{

    static void Main()

    {

        User user = new User();

        user.Password = "SecurePass123";  

        user.ShowMaskedPassword();

    }

}

Output:

Output

Password is set (hidden for security).

Explanation:

In this instance, we are demonstrating the utilization of a Password attribute, enabling the designation of a confidential field that the system verifies without disclosing the actual password. This approach upholds security measures by limiting external entry to delicate information while permitting data input.

Accessor Accessibility in C#

C# additionally allows access modifiers (such as private, protected) to be applied directly to accessors under certain rules:

  • Only properties having both get and set capabilities can have distinct access levels for each.
  • Interfaces do not allow accessor modifiers.
  • The accessor modifier of overridden properties must match that of the base property.
  • Types of Properties

C# features six main categories of properties, each fulfilling a unique access need for encapsulated fields.

The <style> section showcases a diagram with a stylish design. It features a background created using a linear gradient with specific color codes, a rounded border with a 12-pixel radius, ample padding of 40 pixels, and a margin of 20 pixels on the top and bottom. The content is centered within the diagram for a neat appearance. The diagram includes an icon with a font size of 3rem and some accompanying text styled with a font size of 1rem in a color shade of #9ca3af. This design is visually appealing and enhances the overall presentation of the content. </style>

Here, we will explore each of these characteristics individually.

1) Read-Only Property

In C# programming, a Read-Only Property offers managed access to a private field's value, ensuring that it cannot be modified externally. This type of property solely includes the get accessor.

Syntax:

It has the following syntax:

Example

public DataType PropertyName

{

    get

    {

        return _fieldName;

    }

}

C# Read-Only Property Example

Let's consider a scenario to demonstrate the Read-only attribute in C#.

Example

Example

using System;  

       public class Employee  

        {  

            private static int counter;  

      

            public Employee()  

            {  

                counter++;  

            }  

            public static int Counter  

            {  

                get  

                {  

                    return counter;  

                }  

             }  

       }  

       class TestEmployee{  

           public static void Main(string[] args)  

            {  

                Employee e1 = new Employee();  

                Employee e2 = new Employee();  

                Employee e3 = new Employee();  

                //e1.Counter = 10;//Compile Time Error: Can't set value  

      

                Console.WriteLine("No. of Employees: " + Employee.Counter);  

            }  

        }

Output:

Output

No. of Employees: 3

Explanation:

Within the Employee class, the Counter attribute is immutable, featuring solely a getter method that retrieves a static variable monitoring the quantity of Employee instances generated.

2) Write-Only Property

In C# development, the Write-Only Property enables the assignment of a value to a field while restricting external access for reading. This type of property exclusively includes the set accessor.

Syntax:

It has the following syntax:

Example

public DataType PropertyName

{

    set

    {

        _fieldName = value;

    }

}

C# Write-Only Property Example

Let's consider a scenario to demonstrate the Write-Only attribute in the C# programming language.

Example

Example

using System;

class UserAccount

{

    private string passwordHash;

    public string Password

    {

        set

        {

           passwordHash = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value));

        }

    }

    public void ShowHashedPassword()

    {

        Console.WriteLine("Hashed Password (internal use): " + passwordHash);

    }

}

class Program

{

    static void Main()

    {

        UserAccount user = new UserAccount();

        user.Password = "Secure123";

        user.ShowHashedPassword();

    }

}

Output:

Output

Hashed Password (internal use): U2VjdXJlMTIz

Explanation:

In this example, we have taken the UserAccount class that defines a write-only property, Password, with a set accessor that encodes and stores the password internally. It avoids external programs from accessing critical data, which guarantees security while allowing for regulated input.

3) Read-Write Property

The Read-Write Property stands out as the most commonly used form of C# property. It incorporates both get and set accessors, enabling operations for both retrieval and assignment.

Syntax:

It has the following syntax:

Example

public DataType PropertyName

{

    get

    {

        return _fieldName;

    }

    set

    {

        _fieldName = value;

    }

}

C# Read-Only Property Example

Let's consider an example to demonstrate the Read-Only attribute in C#.

Example

Example

using System;

class Employee

{

    private int salary;

    public string Name 

    {

        get; set;

    }

    public int Salary

    {

        get 

        {

            return salary; 

        }

        set

        {

            if (value >= 30000)

                salary = value;

            else

                Console.WriteLine("Salary must be at least 30000.");

        }

    }

    public void Display()

    {

        Console.WriteLine($"Employee Name is: {Name}\nEmployee Salary is: {Salary}");

    }

}

class C# Tutorial

{

    static void Main()

    {

        Employee emp = new Employee();

        emp.Name = "Alice";

        emp.Salary = 25000;  

        emp.Salary = 45000;  

        emp.Display();

    }

}

Output:

Output

Salary must be at least 30000.

Employee Name is: Alice

Employee Salary is: 45000

Explanation:

In this instance, we've chosen the Name attribute, an auto-implemented property enabling direct read and write operations. Subsequently, the Salary attribute employs a private backing field along with get/set accessors; the set accessor enforces a condition that the salary should not fall below 30,000, triggering a warning message if it does.

4) Auto-Implemented property

In C# development, Auto-Implemented Properties streamline the syntax when property accessors do not involve extra logic. An implicit anonymous backing field is generated by the compiler in this scenario.

Syntax

It has the following syntax:

Example

public DataType PropertyName 

{ get; set; }

C# Auto-Implemented Property Example

Let's consider a scenario to demonstrate the auto-implemented property feature in C#.

Example

Example

using System;

class Book

{

    public string Title { get; set; }

    public string Author { get; set; }

    public int YearPublished { get; set; }

    public void PrintDetails()

    {

        Console.WriteLine($"The title of the book is: {Title}\nThe author's name is: {Author}\nThe year of publication is: {YearPublished}");

    }

}

class Program

{

    static void Main()

    {

        Book book = new Book

        {

            Title = "C# In Depth",

            Author = "Jon Skeet",

            YearPublished = 2023

        };

        book.PrintDetails();

    }

}

Output:

Output

The title of the book is: C# In Depth

The author's name is: Jon Skeet

The year of publication is: 2023

Explanation:

In this instance, the Title, Author, and YearPublished attributes of the Book class are auto-implemented, enabling easy read-write access without requiring separate backing fields.

5) Static Property

In C#, a static property is linked to the entire class rather than any specific instance. This indicates that the value of the static property is common to all instances of the class. When working with static properties, it is necessary to declare the backing field as static as well, if it exists. Static properties find common usage in utility classes, global configurations, and singleton patterns.

Syntax

It has the following syntax:

Example

class ClassName

{

    private static DataType fieldName;

    public static DataType PropertyName

    {

        get

        {

            return fieldName;

        }

        set

        {

            fieldName = value;

        }

    }

}

C# Static Property Example

Consider the following example to demonstrate the static property in C#.

Example

Example

using System;

class Bank

{

    public static decimal InterestRate { get; set; }

    public void DisplayInterestRate()

    {

        Console.WriteLine("Current Interest Rate: " + InterestRate + "%");

    }

}

class Program

{

    static void Main()

    {

        Bank.InterestRate = 4.5m;

        Bank bank1 = new Bank();

        Bank bank2 = new Bank();

        bank1.DisplayInterestRate();  

        bank2.DisplayInterestRate();   

        Bank.InterestRate = 5.0m;

        bank1.DisplayInterestRate();   

        bank2.DisplayInterestRate();   

    }

}

Output:

Output

Current Interest Rate: 4.5%

Current Interest Rate: 4.5%

Current Interest Rate: 5.0%

Current Interest Rate: 5.0%

Explanation:

In this instance, we've utilized a static attribute named InterestRate within the Bank class, a property that is common to all instances of the class. Subsequently, the result demonstrates that modifications to the static attribute impact all objects uniformly.

6) Abstract Property

In C#, an abstract property is a property declared in an abstract class or interface without implementation. Subclasses must override and provide the property's implementation. This approach enforces a consistent structure across different classes while enabling subclasses to introduce distinct functionality.

C# Abstract Property Example

Let's consider an example to illustrate the concept of the abstract property in C#.

Example

Example

using System;

abstract class Shape

{

    public abstract double Area { get; }

    public abstract double Perimeter { get; }

}

class Circle : Shape

{

    private double rad;

    public Circle(double rad)

    {

        this.rad = rad;

    }

    public override double Area

    {

        get { return Math.PI * rad * rad; }

    }

    public override double Perimeter

    {

        get { return 2 * Math.PI * rad; }

    }

}

class C# Tutorial

{

    static void Main()

    {

        Circle circle = new Circle(5);

        Console.WriteLine("Circle Area: " + circle.Area);

        Console.WriteLine("Circle Perimeter: " + circle.Perimeter);

    }

}

Output:

Output

Circle Area: 78.5398163397448

Circle Perimeter: 31.4159265358979

Explanation:

In this instance, we are considering the abstract class Shape, which defines two abstract attributes: area and perimeter, without providing their implementations. The Circle class inherits from Shape and offers specific implementations for these attributes, based on the radius.

Conclusion

In summary, C# properties offer a streamlined approach for interacting with and controlling class fields while upholding the concepts of encapsulation and abstraction. They empower us to regulate the retrieval, assignment, or computation of data without revealing the intricacies of the underlying structure. By leveraging diverse property types, C# equips us with the versatility to address a range of situations. Once proficient in C# properties, we can develop code that is not only more secure and manageable but also clearer to comprehend.

C# Properties FAQS

1) What is a property in C#?

In the C# coding language, a property serves as a class element that offers a versatile approach for accessing, modifying, or calculating the data stored in a private field.

2) Can properties be read or written only in C#?

Yes, employing a get accessor enables us to solely read data. Conversely, utilizing a set accessor enables us to solely write data.

3) What is an auto-implemented property?

In C#, this is a convenient feature where the compiler automatically creates the backing field.

4) Is it possible for a property to contain logic within its get and set methods in C#?

Yes, attributes have the capability to include personalized algorithms for validation or calculations.

5) Are properties methods or variables in C#?

In C#, properties are unique methods that can be interacted with just like fields, providing us with method-like functionality while maintaining field syntax.

Input Required

This code uses input(). Please provide values below: