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
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With