C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Expression-bodied membersC# expression bodied members allows us to define members (property or method) definition in a single expression. This expression is very concise and readable in nature. We can use expression body definition with the following.
C# Expression-bodied members syntax
member => expression; C# Expression-bodied method
It consists of a single expression. If method has a return type, expression must return similar type. Let's see an example. C# Expression-Bodied Method Example
using System;
namespace CSharpFeatures
{
public class Student
{
private string Name { get; set; }
// Expression bodied method
public void ShowName() => Console.WriteLine(Name);
public static void Main()
{
Student student = new Student();
student.Name = "Peter John";
student.ShowName();
}
}
}
Output Peter John C# Expression bodied Property Get
We can use expression body to implement get property. A single expression can be used to set a value for the property. We should not use return statement in this property. Let's see an example, that implements expression body in get property. C# Expression-Bodied Get Property Example
using System;
namespace CSharpFeatures
{
public class ExpressionGet
{
// Expression bodied get property
private static string Name { get => "TheDeveloperBlog"; } // Passing value using expression body
public static void Main()
{
Console.WriteLine(ExpressionGet.Name);
}
}
}
Output TheDeveloperBlog
Next TopicC# Null Propagator
|