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 syntaxmember => expression; C# Expression-bodied methodIt 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 Exampleusing 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 GetWe 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 Exampleusing 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
|