C# Auto Implemented Properties

In the C# programming language, Auto-Implemented Properties are also known as Auto Properties. It provides an easy way to declare properties without explicitly defining a backing field. C# allows the use of automatic properties, where we can include only the get or set field within the property.

C# 3.0 includes a concept of auto-implemented properties that requires no code inside the get and set methods of the class properties. It makes the code concise and readable. The C# compiler creates private fields that correspond to the properties and are accessible using the get and set methods.

Syntax:

The syntax of C# auto-implemented properties is as follows.

Example

Public data_type property_name { get; set; }

In this syntax,

  • Data_type: It specifies the type of data of the property
  • property_name: It defines the name of the property.
  • Simple Auto-Implemented Properties Example in C#

Let us consider an example to demonstrate 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 example, we demonstrate the use of auto-implemented properties: Name, Age, and RollNo. In the main method, we create an object s1 of the employee class and assign values to its properties using the set accessor. After that, we use the set accessor to assign values to the properties, and the get accessor is used to retrieve the values. Finally, we are using the Console.WriteLine method to print the values.

Read-only automatic properties

In the C# programming language , we can create properties that should be assigned only once during object initialization. C# allows read-only auto-implemented properties by using the get accessor. These properties can be initialized through a constructor.

C# Example for Read-only automatic properties

Let us take an example to demonstrate 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 example, we have taken two properties named Name and RollNo that are read-only, auto-implemented properties. These properties are declared using the get accessor, and their values are assigned in the constructor. In the Main method, we create an object and perform the Display method to show the output using Console.WriteLine method.

C# Example to demonstrate Bank Account Credit or Debit Operation

Let us take a real-world example to illustrate the concept of bank account credit or debit operations in C# using the 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 example, we have created a class named Account, which has three properties: AccountNo, HolderName, and Balance. After that, we have utilized the Deposit method and Withdraw method that modify the balance internally. In the Main method, we create an object acc1 of the Account class and perform deposit and withdrawal operations. Finally, we use the Console.WriteLine method to print the output.

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";
    
  • Read-Only Auto-Properties: C# also supports read-only auto-implemented properties using the init accessor. The init accessor allows a property to be assigned only when the object is created or inside the constructor.
  • Example
    
    public string Id { get; init; }
    

    Conclusion

In conclusion, C# auto-implemented properties provide a simple and effective method to define properties without explicitly declaring a backing field. It allows the use of automatic properties where we do not have to define the field for the property, and we simply include write, get, and set within the property. This feature reduces the boilerplate code. It improves the readability and makes the code easier to read and understand.

C# Auto-Implemented Properties FAQs

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

In the C# programming language, Auto-Implemented Properties are also known as Auto Properties. It provides an easy way to declare properties without explicitly defining a backing field. C# 3.0 includes a concept of auto-implemented properties that requires no code inside the get and set methods of the class properties.

2) Why are auto-implemented properties beneficial in C#?

The auto-implemented properties help to reduce the boilerplate code and make the class easier to read and maintain. They simplify the property declaration, which makes the code cleaner and easier to understand.

3) What is the syntax of auto-implemented properties in C#?

The syntax of C# auto-implemented properties is as follows.

Example

Public data_type property_name{ get; set; }

In this syntax,

  • Data_type: It specifies the type of data of the property
  • property_name: It defines the name of the property.

4) Can we initialize auto-implemented properties in C#?

Yes, we can assign default values when declaring the property.

Example

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

5) Can auto-implemented properties be read-only in C#?

Yes, auto-implemented properties in C# can be read-only. We create the 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: