C# Expression Bodied Getters And Setters

In the C# programming language, the expression body is a single-line expression statement. It is commonly used to provide a cleaner and shorter code. It provides a compact way to define methods, constructors, and properties using the => operator.

The expression bodies are useful to define the getter and setter properties to make the code more readable. It removes the unnecessary curly braces and returns the statements.

In C# , the expression-bodied members provide a short and concise syntax to define methods, properties, constructors, finalizers, and indexers. It uses the lambda arrow (=>) syntax. It is useful when a member consists of a single expression.

Expression-bodied members were first introduced in C# 6.0, and expression-bodied property getters/setters were added in C# 7.0.

Syntax

It has the following syntax.

Example

type PropertyName

{

    get => expression;

    set => field = value;

}

In this syntax,

  • Type: It represents the type of data, for example, int, string, double, etc.
  • PropertyName: It defines the name of the property.
  • get: It is the expression-bodied getter properties that return a value.
  • Set: It is the expression-bodied setter properties that assign the value.
  • =>: It is the operator that is used to define the expression.
  • Simple Expression-bodied getters and setters Example

Let us take an example to demonstrate the use of expression-bodied getters and setter properties in C#.

Example

Example

using System;

public class C# Tutorial

{

    private int p;

    public int P

    {

        get => p;          // Getter

        set => p = value;  // Setter

    }

}

class Tech

{

    static void Main()

    {

        C# Tutorial tt = new C# Tutorial();

        tt.P = 1500;                 

        Console.WriteLine("The price is " + tt.P);

    }

}

Output:

Output

The price is 1500

Explanation:

In the above example, we demonstrate the use of expression-bodied getters and setter properties in C#. First, we define the C# Tutorial class that contains a private field p to use expression-bodied syntax for both the get and set accessors. Inside the main method, we create an object of C# Tutorial and assign the value. Finally, we use the Console.WriteLine method to print the output.

C# Example to Calculate Area Using Expression-bodied getter and setter

Let us take an example to calculate the area using expression-bodied getters and setter properties in C#.

Example

Example

using System;

public class Rec

{

    private int w;

    private int h;

    // Expression-bodied getter and setter

    public int Width

    {

        get => w;

        set => w = value;

    }

    public int Height

    {

        get => h;

        set => h = value;

    }

    public int Area => w * h;

}

class C# Tutorial

{

    static void Main()

    {

        Rec r = new Rec();

        r.Width = 10;

        r.Height = 20;

        Console.WriteLine("The Width of the rectangle is " + r.Width );

        Console.WriteLine("The Height of the rectangle is " + r.Height );

        Console.WriteLine("The Area of the rectangle is " + r.Area );

    }

}

Output:

Output

The Width of the rectangle is 10

The Height of the rectangle is 20

The Area of the rectangle is 200

Explanation:

In the above example, we demonstrate the use of expression-bodied getter and setter properties in C#. First, we define the Rec class that contains two private fields, w and h. The properties Width and Height are used for expression-bodied syntax for both get and set accessors. Inside the main method, we create an object of the Rec class to calculate the area of a rectangle. Finally, we use the Console.WriteLine method to print the output.

Advantages of Expression-bodied getter and setter

Several advantages of expression-bodied getter and setter in C# are as follows:

1) Cleaner and Shorter, and Code

In C#, the expression-bodied members help to make the code clearer and shorter by removing unnecessary curly braces { } and return statements. It makes the code more readable, concise, and easier to maintain.

2) Reduces Boiler Plate

In C#, the expression-bodied members help to reduce the boilerplate by removing unnecessary curly braces and the explicit return keyword.

3) Improves Readability

The expression-bodied members help to improve the readability of code because the syntax is simplified. It becomes easier to understand the purpose of getter and setter properties at a glance.

4) Encourages Consistent Coding Style

The expression-bodied members promote a uniform and clean code structure. It helps to define a consistent coding style across the class.

Limitations of Expression-bodied getters and setters

Several limitations of expression-bodied getters and setter properties in C# are as follows:

1) Complex Logic:

The expression-bodied members are not suitable for complex logic. It is best only for simple and single-line logics. When we need additional operations, such as if-else conditions, loops, input validation, or logging, then expression-bodied syntax is not suitable.

2) Limited to a Single Expression:

The expression-bodied members can contain only one expression. It cannot hold multiple lines of code, blocks, or statements.

3) Difficult to Debug:

The expression-bodied members are harder to debug the code inside a single-line expression. The debuggers cannot easily search for errors or trace the execution flow step by step, which makes it more difficult.

4) Reduced Readability for beginners

The arrow expression ( => ) syntax may appear confusing or unfamiliar to beginners. It can reduce readability and make the code harder for new learners to understand.

Conclusion

In conclusion, the expression-bodied getters and setters in C# provide cleaner and shorter code. It improves the readability of code. It removes the unnecessary code and promotes the coding style. It is used to provide a single life definition to the method, constructor, or property. We can use this expression body to define the getter and setter.

C# Expression-bodied getters and setters FAQs

1) What are Expression-bodied getters and setters in C#?

C# expression body is a single-line expression statement. It is used to provide a cleaner and shorter code. It provides a compact way to define methods, constructors, and properties using the => operator. We can use it to define the getter and setter properties and make the code more readable.

2) Which C# version introduced expression-bodied properties?

The expression-bodied properties were introduced in C# 7.0.

3) How do expression-bodied members handle parameters?

In C#, the expression-bodied methods can take parameters just like regular methods. The parameters are declared in the method signature before the => operator.

Example

public int Add(int a, int b) => a + b;

4) What is the benefit of using expression-bodied members?

  • It provides cleaner and concise code.
  • It is used for improving the readability of code.
  • It reduces the boilerplate by removing unnecessary curly braces and the explicit return keyword.

5) What is the syntax of expression-bodied getters and setters in C#?

The syntax of expression-bodied getter and setter properties is.

Example

type PropertyName

{

    get => expression;

    set => field = value;

}

Input Required

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