c# - Lambda operator in set -


can explain purpose of lambda operator in piece of code, do?

public string helloworld {     { return _helloworld; }     set { set(() => helloworld, ref _helloworld, value); } } 

this common pattern extract member name inotifypropertychanged implementation.

usually, want raise propertychanged event propertychangedeventargs property name changed. problem property name string. if rename property, have make sure adjust member name strings too.

in order avoid that, people implement method, e.g. set, takes expression. method uses expression tree extract member name of property. takes name create event arguments , raises event you.


your set equivalent following setter:

set {     if (_helloworld != value)     {         _helloworld = value;         onpropertychanged(new propertychangedeventargs(this, "helloworld"));     } } 

and encapsulated in set method provided base view model.


btw. .net 4.5, can make use of new compiler services make simpler. .net 4.5 comes callermembernameattribute allows implementations of inotifypropertychanged provide utility function automatically gets name of property, don’t have pass lambda expression references property. furthermore, new functionality evaluated @ compile time, same performance when pass string, except don’t need specify string anywhere, you’re safe against refactorings.

this functionality provided mvvm light, , can use different overload of set use it. example this:

set(ref _helloworld, value); 

with c# 6, can use new nameof operator: nameof(helloworld) replaced "helloworld" @ compile time.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -