C# Expression Bodied Members

In the C# programming language, the expression-bodied members provide a short and concise syntax to define methods, properties, constructors, finalizers, and indexers. It uses the lambda arrow (=>) operator. It is mainly used when a member consists of a single expression. It was first introduced in C# 6.0. C# expression-bodied members allow us to define (property or method definitions) in a single expression. This expression is very concise and readable in nature.

Expression-bodied Methods

In the C# programming language , a method is a collection of data members and data methods that perform a given task and return the result to the caller. These methods are written in curly braces{}.

Syntax:

It has the following syntax.

Example

returnType MethodName ( parameterList ) => expression;

In this syntax,

  • returnType: It is the type of value that is returned to the method.
  • MethodName: It is the name of the method.
  • parameterList: It defines the input parameter.
  • Expression: It defines the operation that will execute the code.
  • Simple C# Expression-bodied Members Example:

Let us take an illustrative example to define the expression-bodied methods in C#.

Example

Example

using System;

class Calc

{

    public int Add(int m, int n) => m + n;

    public void Show( string message ) => Console.WriteLine( message );

}

class C# Tutorial

{

    static void Main()

    {

        Calc c = new Calc ();

        int res = c.Add (10, 20);

        Console.WriteLine ("The result is " + res);

        c.Show("This is an expression-bodied method example.");

    }

}

Output:

Output

The result is 30

This is an expression-bodied method example.

Explanation:

In the above example, we demonstrate the use of an expression-bodied method in C#. Here, the Add method uses the arrow expression (=>) to return the sum of two numbers. In the main method, we create an object of the Calc class and call the Add method. After that, the Show method displays the output using the Console.WriteLine method.

Expression-bodied Void Methods

In C#, the void method is a type of method that does not return any value. When a method contains a single statement, we can define it using an expression-bodied syntax using the => operator.

Syntax:

It has the following syntax:

Example

void MethodName(parameters) => singleStatement;

In this syntax,

  • void: The void means the method that does not return a value.
  • MethodName: It represents the name of the method.
  • Parameters: It defines the input parameter.
  • =>: It is the operator that is used to define the expression.
  • C# Expression-bodied Example using Void Methods

Let us take an illustrative example to define the expression-bodied void method in C#.

Example

Example

using System;

class C# Tutorial

{

    public void Show(string message) => Console.WriteLine(message);

}

class Tech

{

    static void Main()

    {

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

        t.Show("This is an expression-bodied void method example.");

    }

}

Output:

Output

This is an expression-bodied void method example.

Explanation:

In the above example, we demonstrate the use of expression-bodied using a void method. First, we declare a C# Tutorial class that contains the void Show method, and it contains only one statement. In the Tech class, we create an object of the C# Tutorial class and call the Show method. Finally, we use the Console.WriteLine method to print the output.

Expression-bodied Property

The expression-bodied properties allow accessor properties (getter or setter) to contain only a single statement. It has been written using the => syntax. It has two types.

  • Read-only Properties
  • Non-Read Only Properties

Now, we will discuss these properties one by one.

Read-only Properties

In the C# programming language, the Read-only properties are those types of properties that include only a get accessor. It allows us to retrieve the value, but does not allow modification from outside the class.

Syntax:

It has the following syntax.

Example

type PropertyName => expression;

C# Expression-bodied Members Example using the read-only property

Let us take an illustrative example to illustrate the read-only properties in C#.

Example

Example

using System;

public class C# Tutorial

{

    private int val = 10;

    // Read-only property

    public int Value => val;

    // Getter and Setter expression-bodied property

    public int Number

    {

        get => val;

        set => val = value;

    }

    // Calculated read-only property

    public int Double => val * 2;

    // Auto-property with private setter

    public int Id { get; private set; } = 101;

}

class Program

{

    static void Main()

    {

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

        Console.WriteLine("The Value is " + t.Value );

        Console.WriteLine("The Double is " + t.Double );

        Console.WriteLine("The ID is " + t.Id );

        t.Number = 25;

        Console.WriteLine(" After setting the Number, the Value is: " + t.Value );

        Console.WriteLine("After setting the Number, the Double is: " + t.Double );

    }

}

Output:

Output

The Value is 10

The Double is 20

The ID is 101

After setting the Number, the Value is: 25

After setting the Number, the Double is: 50

Explanation:

In the given example, we demonstrate the expression-bodied and auto-implemented properties in C#. First, the value property is a read-only expression-bodied property that returns the private field val. The Number property has both get and set accessors. The Double property is a read-only property that always returns twice the value of val. The Id is an auto-implemented property. When the number is set to 25, both Value and Double change because they are in the same field.

Non-Read-only Properties

In C#, the non-read-only properties are properties that include both a getter and a setter. It allows us to retrieve the value and also modify values. It helps to provide full read and write accessibility when the value needs to be changed during the program execution.

C# Expression-bodied Members Example using non-read-only properties

Let us take an illustrative example to define the non-read-only properties using expression bodies in C#.

Example

Example

using System;

public class Product

{

    private int price;

    public int Price

    {	

        get => price;          // getter

        set => price = value;  // setter

    }

    private string name;

    public string Name

    {

        get => name;

        set => name = value;

    }

}

class C# Tutorial

{

    static void Main()

    {

        Product p = new Product();

        p.Price = 500;

        p.Name = "Laptop";

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

        Console.WriteLine("The Product Price is " + p.Price );

    }

}

Output:

Output

The Product Name is Laptop

The Product Price is 500

Explanation:

In the given example, we create the Product class that contains the two fields: price and name. In the main method, we create a Product object, where the Price of the object is set to 500, and the Name is set to Laptop. After that, we use the Console.WriteLine method to print the updated values.

Expression-bodied Indexers

In C#, the indexers accessors can also be written using the expression-bodied syntax. It is similar to the expression-bodied and methods. It allows us to define getter and setter properties of an indexer. It makes the code concise and readable.

Syntax:

It has the following syntax.

Example

[access-modifier] [qualifiers] return-type this[ [parameters] ] => expression;

C# Expression-bodied Indexers Example

Let us take an illustrative example to demonstrate the expression-bodied indexers in C#.

Example

Example

using System;

public class NumList

{

    private int[] n = { 100, 200, 300, 400, 500 };

    // getter and setter

    public int this[ int index ]

    {

        get => n[index];

        set => n[index] = value;

    }

}

class C# Tutorial

{

    static void Main()

    {

        NumList list = new NumList();

        Console.WriteLine("The original value at index 2 is " + list[2] );

        list[2] = 990;

        Console.WriteLine("The updated value at index 2 is " + list[2] );

    }

}

Output:

Output

The original value at index 2 is 300

The updated value at index 2 is 990

Explanation:

In the above example, we create a class NumList that contains an integer array. The indexers allow access and modification of elements using brackets. The get expression returns the value stored at the specific index, and the set expression assigns a new value to that index. In the Main method, we first retrieve the value and then print the original value at index 2. After that, we use the indexer for updating the value. Finally, we use the Console.WriteLine method to print the output.

Expression-bodied Constructor in C#

In C#, the expression-bodied technique can also be used to define a constructor in a single statement. It allows the constructor to initialize variables and perform simple operations using the => operator. It makes the code shorter and more readable.

C# Expression-bodied Constructor Example

Let's consider an example to demonstrate the Expression-bodied Constructor in C#.

Example

Example

using System;

public class C# Tutorial

{

    public string Name { get; }

    // Expression-bodied constructor

    public C# Tutorial(string name) => Name = name;

}

class tech

{

    static void Main()

    {

        C# Tutorial t = new C# Tutorial("Laptop");

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

    }

}

Output:

Output

The Product Name is Laptop

Explanation:

In the given example, we have taken a C# Tutorial class that use an expression-bodied constructor to initialize the Name property in a single line. When we create an object using new C# Tutorial("Laptop"), the constructor assigns the value to the Name property. Finally, it prints the assigned name on the screen.

Expression-bodied Deconstructor in C#

In C#, an expression-bodied deconstructor is a concise way to define a deconstruct method using the => expression-bodied.

C# Expression-bodied Deconstructor Example

Let us take an illustrative example to define the expression-bodied deconstructor in C#.

Example

Example

using System;

public class C# Tutorial

{

    public string Name { get; }

    public int Age { get; }

    public C# Tutorial(string name, int age)

    {

        Name = name;

        Age = age;

    }

    // Expression-bodied Deconstructor

    public void Deconstruct(out string name, out int age)

        => (name, age) = (Name, Age);

}

class tech

{

    static void Main()

    {

        C# Tutorial p = new C# Tutorial("John", 22);

        // Deconstruction assignment

        var (n, a) = p;

        Console.WriteLine("The name is " + n + ", and the age is " + a );

    }

}

Output:

Output

The name is John, and the age is 22

Explanation:

In the above example, we have taken the C# Tutorial class that uses an expression-bodied deconstruct method to quickly assign the object's Name and Age to output variables. When we write var (n, a) = p., C# automatically calls Deconstruct and extracts these values into n and a. Finally, we use the Console.WriteLine method to print the output.

Conclusion

In conclusion, expression-bodied members in C# provide a short and concise syntax to define methods, properties, constructors, finalizers, indexers, and many more. It uses the lambda arrow (=>) operator. It reduces the boilerplate by removing unnecessary curly braces and the explicit return keyword. These are very useful for short logic, one-line operations, and computed properties, which help us to write modern, readable, and maintainable code. Overall, the expression-bodied members are widely utilized features to create clean and expressive applications in C#.

C# Expression-bodied members FAQs

1) What are the expression bodies members in C#?

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 (=>) operator. It is mainly used when a member consists of a single expression. It was first introduced in C# 6.0.

2) How do expression-bodied members handle parameters in C#?

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;

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

There are several benefits of using expression-bodied members in C#. Some of them are as follows:

  • 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.

4) What is the syntax of expression-bodied members in C#?

It has the following syntax.

Example

returnType MethodName ( parameterList ) => expression;

In this syntax,

  • returnType: It is the type of value that is returned to the method.
  • MethodName: It is the name of the method.
  • parameterList: It defines the input parameter.
  • Expression: It defines the operation that will execute the code.

5) Are indexers supported as expression-bodied members in C#?

Yes, the indexers are supported as expression-bodied members in C#.

Example

public int this[int i]

{

    get => arr[i];

    set => arr[i] = value;

}

Input Required

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