C# Auto Implemented Properties

In C# coding language, Auto-Implemented Properties are commonly referred to as Auto Properties. They offer a convenient method to declare properties without the need to explicitly specify a supporting field. C# permits the utilization of automatic properties, enabling developers to incorporate solely the get or set field within the property.

The <style> component includes a CSS code snippet for a placeholder diagram. The diagram is styled with a gradient background, rounded borders, padding, and centered text alignment. It also features an icon with a size of 3rem and text with a color of #9ca3af and font size of 1rem.

C# 3.0 introduces the idea of auto-implemented properties, which do not need any explicit code within the get and set methods of class properties. This feature enhances code brevity and clarity. The compiler in C# generates private fields aligned with the properties, which can be accessed through the get and set methods.

Syntax:

The format for C# auto-implemented properties is as shown below.

Example

Public data_type property_name { get; set; }

In this particular format,

  • Data_type: It indicates the data type of the attribute
  • property_name: It establishes the title of the attribute.
  • Simple Auto-Implemented Properties Example in C#

Let's explore an illustration to showcase the auto-implemented properties in C#.

Example

Example

using System;

class Employee

{

    // Auto-implemented properties

    public string Name { get; set; }

    public int Age { get; set; }

    public int RollNo { get; set; }

}

class C# Tutorial

{

    static void Main()

    {

        // Creating an object of Student

        Employee s1 = new Employee ();

        // Setting property values

        s1.Name = "Albert";

        s1.Age = 20;

        s1.RollNo = 101;

        // Getting property values

        Console.WriteLine(" The name is " + s1.Name );

        Console.WriteLine(" The age is " + s1.Age );

        Console.WriteLine(" The roll number is " + s1.RollNo );

    }

}

Output:

Output

The name is Albert

The age is 20

The roll number is 101

Explanation:

In this illustration, we showcase the implementation of auto-implemented properties: Name, Age, and RollNo. Within the main function, we instantiate an instance s1 of the employee class and set values to its properties via the set accessor. Subsequently, we utilize the set accessor to assign values to the properties and retrieve the values using the get accessor. Ultimately, we employ the Console.WriteLine method to display the values.

Read-only automatic properties

In C# programming, developers have the ability to define properties that are meant to be set only once when an object is being initialized. This can be achieved by utilizing read-only auto-implemented properties with the get accessor, which enables the properties to be set via a constructor.

C# Example for Read-only automatic properties

Let's consider an example to illustrate the read-only automatic properties in C#.

Example

Example

using System;

class Information

{

    // Read-only auto-implemented properties

    public string Name { get; }

    public int RollNo { get; }

    // Constructor 

    public Information(string name, int rollNo)

    {

        Name = name;

        RollNo = rollNo;

    }

    public void Display()

    {

        Console.WriteLine("The Name is " + Name);

        Console.WriteLine("The Roll Number is " + RollNo);

    }

}

class Program

{

    static void Main()

    {

        Information info = new Information("Olivia", 110);

        info.Display();

    }

}

Output:

Output

The Name is Olivia

The Roll Number is 110

Explanation:

In this instance, we've defined two read-only auto-implemented properties: Name and RollNo. These properties are set with the get accessor and initialized within the constructor. Within the Main function, an object is instantiated, and the Display method is executed to exhibit the output via Console.WriteLine.

C# Example to demonstrate Bank Account Credit or Debit Operation

Let's consider a practical scenario to demonstrate the concept of depositing or withdrawing funds from a bank account in C# by utilizing auto-implemented properties.

Example

Example

using System;

class PointAccount

{

    public string AccNo { get; set; }

    public string HName { get; set; }

    public double Bal { get; private set; } // 

    public PointAccount(string accNo, string name, double initialBal)

    {

        AccNo = accNo;

        HName = name;

        Bal = initialBal;

    }

    public void PointDeposit(double amt)

    {

        if (amt > 0)

        {

            Bal += amt;

           Console.WriteLine("Amount Deposited: " + amt + ", Current Balance: " + Bal);

        }

        else

        {

      Console.WriteLine("Please enter a valid deposit amount.");

        }

    }

    public void PointWithdraw(double amt)

    {

        if (amt > 0 && amt <= Bal)

        {

            Bal -= amt;

Console.WriteLine("You have withdrawn " + amt + ". Your remaining balance is " + Bal + ".");

        }

        else

        {

Console.WriteLine("Withdrawal failed due to insufficient balance.");

        }

    }

}

class Account

{

    static void Main()

    {

        PointAccount acc1 = new PointAccount("12345", "Peter", 5000);

        Console.WriteLine("The Account Holder Name is " + acc1.HName);

        Console.WriteLine("The Account Number is " + acc1.AccNo);

        Console.WriteLine("The Initial Balance is " + acc1.Bal);

        acc1.PointDeposit(2500);

        acc1.PointWithdraw(1200);

    }

}

Output:

Output

The Account Holder Name is Peter

The Account Number is 12345

The Initial Balance is 5000

Amount Deposited: 2500, Current Balance: 7500

You have withdrawn 1200. Your remaining balance is 6300.

Explanation:

In this instance, we've established a class called Account, containing three attributes: AccountNo, HolderName, and Balance. Subsequently, we've employed the Deposit function and Withdraw function to adjust the balance internally. Within the Main function, we instantiate an object acc1 from the Account class and execute deposit and withdrawal procedures. Ultimately, we employ the Console.WriteLine function to display the result.

Features of Auto-Implemented Properties

Several advantages of auto-implemented properties in C# are as follows.

  • Reduce Code: The auto-implemented properties in C# reduce the boilerplate code and make the code easier to read and maintain.
  • Improved Readability: The concise syntax of auto-implemented properties makes the code easier to read and understand.
  • Support for Property Initializers: Auto-implemented properties can be initialized with a default value at the time of declaration.
  • Example
    
    public string Name { get; set; } = "Unknown";
    

In C#, read-only auto-implemented properties are also possible with the use of the init accessor. This special accessor restricts the assignment of a property's value to only occur during object creation or within the constructor function.

Example

public string Id { get; init; }

Conclusion

In summary, C# auto-implemented properties offer a straightforward and efficient approach to specifying properties without the need to explicitly declare a backing field. They enable the use of automatic properties, eliminating the necessity of defining a field for the property, and instead incorporating write, get, and set directly within the property. This functionality minimizes redundant code, enhances readability, and simplifies comprehension of the code.

C# Auto-Implemented Properties FAQs

1) What are auto-implemented properties in C#?

In C# programming, Auto-Implemented Properties, commonly referred to as Auto Properties, offer a convenient method to define properties without the need to explicitly specify a supporting field. C# 3.0 introduces the idea of auto-implemented properties, which eliminate the necessity for any code within the get and set functions of the class properties.

Auto-implemented properties in C# are advantageous for several reasons:

  • They provide a concise syntax for defining properties without explicitly writing the backing field.
  • They enable faster development by reducing the amount of boilerplate code that needs to be written.
  • They help improve code readability by simplifying the property declaration process.
  • They are particularly useful in scenarios where the property logic does not require additional custom implementation.
  • They contribute to cleaner and more maintainable code by promoting a more streamlined approach to property definition.

Auto-implemented properties aid in minimizing redundant code and enhancing the readability and maintainability of a class. They streamline the process of declaring properties, resulting in more concise and comprehensible code.

Auto-implemented properties in C# have the following syntax:

Example

public string PropertyName { get; set; }

The format for C# auto-implemented properties is as described below.

Example

Public data_type property_name{ get; set; }

In this coding structure,

  • Data_type: Indicates the data type of the property
  • property_name: Specifies the name assigned to the property.

4) Is it possible to set default values for auto-implemented properties in C#?

Yes, it is possible to set default values during property declaration.

Example

public int Age { get; set; } = 18;

5) Is it possible for auto-implemented properties to be read-only in C#?

Yes, in C#, auto-implemented properties can also be defined as read-only. We can easily generate an auto-implemented property.

Example

public class Person

{

    public string Id { get; }

    public Person(string id)

    {

        Id = id;

    }

}

Input Required

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