28

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?

kyrylomyr
  • 12,192
  • 8
  • 52
  • 79
user2818430
  • 5,853
  • 21
  • 82
  • 148

3 Answers3

26

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

haim770
  • 48,394
  • 7
  • 105
  • 133
  • 5
    Not just saving keystrokes, but also easier to read if you have a lot of them - less clutter. (That is, assuming the reader is familiar with this syntax.) – Bob Dec 07 '15 at 03:11
12

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.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
5

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")