Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression bodied get / set accessors feature in c# 7.0

Tags:

c#

.net

c#-7.0

I'm having this code in a class

private string test;
public string Test
{
    get =>  test;
    set => test = value;
}

But the compiler won't let me compile. It says

CS1043 { or ; expected 
CS1513 } expected

I'm using VS 2017 and targeting .NET FW 4.6 with a MVC 5 Project

Any idea why it isn't working?

like image 335
gsharp Avatar asked Apr 28 '17 13:04

gsharp


People also ask

Which is correct syntax for expression-bodied function?

The Syntax of expression body definition is, member => expression; where expression should be a valid expression and member can be any from above list of type members.

What is an expression-bodied method?

An expression-bodied method consists of a single expression that returns a value whose type matches the method's return type, or, for methods that return void , that performs some operation.

Which operator can you use to code an expression-bodied property or method?

The expression-bodied syntax can be used when a member's body consists only of one expression. It uses the =>(fat arrow) operator to define the body of the method or property and allows getting rid of curly braces and the return keyword. The feature was first introduced in C# 6.

Can C# expression-bodied method contain multiple expression?

Yes, you can.


Video Answer


1 Answers

You have to set the compiler to version 7 in your project.

Project properties → (tab) Build → Advanced → Language version = C# 7.0

UPDATE BY @gsharp

check also your (NuGet) reference to the .NET Compiler platform Microsoft.Net.Compilers.

like image 80
Igor Avatar answered Oct 30 '22 15:10

Igor