Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert to expression body does not seem to work?

Tags:

c#

lambda

I have the following code:

public bool IsUser
{
    get { return false; }
}

Now Resharper suggests I write it to:

public bool UseBands => false;

However this does not compile and my compiler complains that I should add a ";"?

Update

I have experienced this problem using Resharper 9 on Visual Studio 2013 Update 4. Resharper seems to look in the project properties, which suggestion rules it should apply. If you encounter this problem, then probably as mentioned by Szer, you have enabled the C# 6.0 Language Level.

To disable it, simply click on your project in the solution explorer and then set the C# Language Level to something other than C# 6.0.

PS: due to my limited knowledge of changing the settings of my project I did not knew there was a function to set this. Though I do not remember to have changed it (the C# Language Level). Thank you for all your help.

like image 804
Snowflake Avatar asked Feb 05 '15 09:02

Snowflake


1 Answers

According to MSDN this is one of C#6 features. ReSharper9 partially supports it and you probably enabled it a little bit early.

Quote from MSDN:

Expression-bodied function members allow methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.

Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”:

public Point Move(int dx, int dy) => new Point(x + dx, y + dy); 
public static Complex operator +(Complex a, Complex b) => a.Add(b); 
public static implicit operator string(Person p) => "\{p.First} \{p.Last}";

The effect is exactly the same as if the methods had had a block body with a single return statement.

For void returning methods – and Task returning async methods – the arrow syntax still applies, but the expression following the arrow must be a statement expression (just as is the rule for lambdas):

public void Print() => Console.WriteLine(First + " " + Last);

Properties and indexers can have getters and settersgetter-only properties and indexers can have an expression body:

public string Name => First + " " + Last; 
public Customer this[long id] => store.LookupCustomer(id);

Note that there is no get keyword: it is implied by the use of the expression body syntax.

More here: http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx

like image 92
Szer Avatar answered Sep 19 '22 17:09

Szer