Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS2017 with new getter/setter syntax: How to write multiple lines in the setter?/ [closed]

I am using .NET Framework 4.5.2, VS2017. VS2017 has got new syntax for getter and setter. Now the property with getter setter looks like below:

public string Name { get => _name; set => _name = value; }

I have to write the below property. How can I write the setter with lambda expression set=> ?

public int EmployeeNumber
    {
        get => _employeeNumber;
        set { _employeeNumber = value; OnPropertyChanged("EmployeeNumber");}
    }

such as something like this:

public int EmployeeNumber
{
   get => _employeeNumber;
   set =>{ _employeeNumber = value;OnPropertyChanged("EmployeeNumber"); }
}

For the above setter, I get 3 errors:

CS1525: Invalid expression term {
CS1002: ; expected
CS1014: A get or set accessor expected
like image 842
Sunita Avatar asked Oct 31 '17 23:10

Sunita


1 Answers

Ok, lets go over this again. You want to write

public int EmployeeNumber 
{
    set 
    { 
        _employeeNumber = value;
        OnPropertyChanged("EmployeeNumber");
    } 
}

Like this:

public int EmployeeNumber 
{
    set => 
    { 
        _employeeNumber = value;
        OnPropertyChanged("EmployeeNumber");
    } 
}

The question is why? The whole point about expression bodied function members is to make things more concise and readable avoiding curly braces, return keywords, etc.:

public int Foo => foo

Instead of,

public int Foo { return foo; }

What you are attempting to do doesn't make it more readable and adds two useless extra tokens. That seems like an awful bargain.

As a general rule, you shouldn't use (or can't use) the => syntax when the code on the right side:

  1. Doesn't return anything (throwing exceptions is the exception, pun intended)
  2. Is made up of more than one expression.
  3. Is there because of the side effects it produces.

Of course rule nº3 is mine alone, I'm not aware of any coding style recommendations on this matter but I tend to avoid this syntax unless I'm dealing with no side effects producing methods.

like image 58
InBetween Avatar answered Oct 29 '22 23:10

InBetween