In C# programming, expression-bodied members offer a concise syntax for defining methods, properties, constructors, finalizers, and indexers using the lambda arrow (=>) operator. This feature is particularly useful for members that involve only one expression. Expression-bodied members were initially introduced in C# version 6.0, enabling the definition of properties or methods within a single expression, promoting readability and brevity.
The CSS code snippet below demonstrates the styling for a placeholder diagram:
.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }
Expression-bodied Methods
In C#, a method consists of data members and operations that carry out a specific function and provide an output to the invoker. These functions are enclosed within curly braces {}.
Syntax:
It has the following syntax.
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's consider an example to explain what expression-bodied methods are in C#.
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:
The result is 30
This is an expression-bodied method example.
Explanation:
In the example provided, we showcase the implementation of an expression-bodied method in C#. In this scenario, the Add function employs the arrow expression (=>) to deliver the total of two numerical values. Within the primary function, an instance of the Calc class is instantiated, and the Add method is invoked. Subsequently, the Show method exhibits the result utilizing the Console.WriteLine function.
Expression-bodied Void Methods
In C#, a void method is a method type that does not yield any output. If a method consists of a solitary statement, it can be declared using an expression-bodied format employing the => symbol.
Syntax:
It has the following syntax:
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's consider a practical example to explain the expression-bodied void method in C#.
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:
This is an expression-bodied void method example.
Explanation:
In the example provided, we showcase the implementation of expression-bodied members in a void method. Initially, we define a C# Tutorial class incorporating the void Show method with a single statement. Within the Tech class, an instance of the C# Tutorial class is instantiated, and the Show method is invoked. Ultimately, the output is displayed using the Console.WriteLine method.
Expression-bodied Property
The expression-bodied properties enable accessor properties, whether getter or setter, to consist of just one statement and are defined using the => syntax. There are two categories:
- Properties that are read-only
- Properties that are not read-only
Now, we will discuss these properties one by one.
Read-only Properties
In C# programming, Read-only properties are properties that have only a get accessor. They enable retrieval of values but prevent external modifications to the class.
Syntax:
It has the following syntax.
type PropertyName => expression;
In this instance, an illustration of C# Expression-bodied Members is provided, showcasing the utilization of the read-only property.
Let's consider a practical example to demonstrate the immutable characteristics in C#.
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:
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 this example, we showcase the usage of expression-bodied and auto-implemented properties in C#. Initially, the value property is an expression-bodied property set for read-only access, retrieving the value from the private field named val. The Number property is equipped with both get and set accessors. For the Double property, it functions as a read-only property that consistently yields a value equal to twice the value stored in val. Lastly, the Id property is an auto-implemented property. Notably, modifying the number to 25 triggers changes in both the Value and Double properties since they share the same underlying field.
Non-Read-only Properties
In the C# programming language, non-readonly properties are properties that contain both a getter and a setter. This enables us to both access and update the value, offering complete read and write capabilities for altering values during program execution.
In this example, we will demonstrate the utilization of C# expression-bodied members with properties that are not read-only.
using System;
public class Person
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
public string DisplayName => "Name: " + _name;
}
class Program
{
static void Main()
{
Person person = new Person();
person.Name = "Alice";
Console.WriteLine(person.DisplayName);
}
}
Let's consider a practical example to explain the mutable properties using expression bodies in C#.
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:
The Product Name is Laptop
The Product Price is 500
Explanation:
In this provided illustration, we define the Product class which holds the attributes: price and name. Within the primary function, an instance of Product is instantiated, with the price set to 500 and the name set to Laptop. Subsequently, we employ the Console.WriteLine function to display the modified values.
Expression-bodied Indexers
In C#, the accessors for indexers can alternatively be implemented using the expression-bodied syntax. This syntax is akin to expression-bodied methods, enabling the definition of getter and setter properties for an indexer. This approach enhances code brevity and readability.
Syntax:
It has the following syntax.
[access-modifier] [qualifiers] return-type this[ [parameters] ] => expression;
C# Expression-bodied Indexers Example
Let's consider a practical example to showcase the expression-bodied indexers in C#.
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:
The original value at index 2 is 300
The updated value at index 2 is 990
Explanation:
In the provided illustration, a NumList class is established to store an array of integers. Through the use of indexers, elements can be accessed and altered by utilizing square brackets. The get expression retrieves the stored value at a defined index, while the set expression updates the value at that index. Within the Main method, the initial value at index 2 is obtained and displayed. Subsequently, the indexer is employed to modify the value. The output is then printed using the Console.WriteLine method.
Expression-bodied Constructor in C#
In C#, the expression-bodied method is applicable for defining a constructor within a single statement. This method enables the constructor to set initial values for variables and execute basic tasks by utilizing the => operator. This approach results in more concise and easily comprehensible code.
C# Expression-bodied Constructor Example
Let's examine a sample to illustrate the Expression-bodied Constructor in C#.
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:
The Product Name is Laptop
Explanation:
In this example, we've utilized a C# Tutorial class demonstrating the implementation of an expression-bodied constructor for initializing the Name property in a concise manner. By instantiating a new object with the name "Laptop", this constructor effectively sets the value to the Name property, displaying the assigned name on the output screen.
Expression-bodied Deconstructor in C#
In C#, a deconstructor implemented with an expression-bodied syntax provides a succinct approach to defining a deconstruct method utilizing the => expression-bodied syntax.
C# Expression-bodied Deconstructor Example
Let's consider a practical example to explain the concept of expression-bodied deconstructor in C#.
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:
The name is John, and the age is 22
Explanation:
In the preceding illustration, we demonstrated the implementation of a C# Tutorial class featuring an expression-bodied deconstruct technique for efficiently assigning the object's Name and Age to output variables. By utilizing var (n, a) = p., C# invokes the Deconstruct method automatically to retrieve and assign these values to n and a. Subsequently, we employ the Console.WriteLine function to display the resultant output.
Conclusion
In summary, expression-bodied members in C# offer a succinct and compact way to declare methods, properties, constructors, finalizers, indexers, and various other elements. They leverage the lambda arrow (=>) operator to streamline syntax. By eliminating superfluous curly braces and the explicit return keyword, they minimize redundancy. These features are particularly beneficial for concise logic, single-line tasks, and computed properties, enhancing the ability to craft contemporary, understandable, and sustainable code. Ultimately, expression-bodied members are extensively employed functionalities for producing well-structured and eloquent applications in C#.
C# Expression-bodied members FAQs
1) What are the expression bodies members in C#?
In C#, the expression-bodied members offer a succinct and clear syntax for defining methods, properties, constructors, finalizers, and indexers. This feature utilizes the lambda arrow (=>) operator and is particularly handy when a member contains only one expression. The concept of expression-bodied members was initially presented in C# 6.0.
Expression-bodied members in C# can handle parameters by allowing developers to write concise, one-liner methods or properties using lambda expressions. This feature enables the creation of compact and readable code for methods that have a single statement or expression.
In C#, expression-bodied methods have the capability to accept parameters similar to conventional methods. These parameters are specified in the method signature prior to the => operator.
public int Add(int a, int b) => a + b;
Expression-bodied members provide a more concise and readable way to define members, such as properties, methods, and constructors, in C# code. They offer a shorthand syntax that can make the code easier to understand and maintain.
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) How is the syntax of expression-bodied members defined in C#?
It has the following syntax.
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) Is it possible to use indexers as expression-bodied members in C#?
Yes, indexers in C# are compatible with expression-bodied members.
public int this[int i]
{
get => arr[i];
set => arr[i] = value;
}