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?
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?
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
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.
This is not actually a variable initialization, this binds the lambda expression "string.Empty" to "m", so whenever you dereference "m", it will actually evaluate your lambda expression.
For further reading check out this github page (section "Expression-bodied function member")