Snowflake Snowflake - 1 year ago 68
C# Question

Convert to expression body does not seem to work?

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 ";"?


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.

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download