Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This question already has an answer here:

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?

share|improve this question

marked as duplicate by Yuval Itzchakov c# 2 hours ago

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

12  
Please note that this syntax is only available in C# 6.0 language version. – Tamas Ionut yesterday
    
Great new feature, adds more code brevity IMO! – Daniel Hakimi yesterday

3 Answers 3

up vote 18 down vote accepted

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

share|improve this answer
4  
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 21 hours ago

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.

share|improve this answer

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

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.