Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lambda variable initialization [duplicate]

Tags:

c#

c#-6.0

Today for the first time I seen something similar to this:

private string m => string.Empty; 

using lambda to initialize a variable. Why doing it like this and what are the benefits?

like image 311
user2818430 Avatar asked Dec 06 '15 21:12

user2818430


2 Answers

It's called Expression-Bodied Properties and it's merely a shortcut for getter-only properties:

private string m {     get { return string.Empty; } } 

As for the benefits of this approach, I guess you can treat it as syntactic sugar that is only saving you some keystrokes.

See Roslyn Wiki

like image 66
haim770 Avatar answered Oct 06 '22 23:10

haim770


It's not a variable, it's an expression bodied property. A read-only property, in your case returning string.Empty.

It's the same as

private string m { get { return string.Empty; } } 

It's one of the new features introduced in C# 6.0. The benefit is shorter, more concise code. Especially if you have a class with a lot of simple read-only properties.

If you want to see a real-world example of this syntax, check the this post on Eric Lippert's blog. As you can see, there's a lot of one-line methods and properties there. Without expression-bodied properties and members, the code would be much longer. And a considerable part of it would be curly braces.

like image 31
Jakub Lortz Avatar answered Oct 06 '22 23:10

Jakub Lortz