c# - Is [CallerMemberName] slow compared to alternatives when implementing INotifyPropertyChanged? -
there articles suggest different ways implementing inotifypropertychanged
.
consider following basic implementation:
class basicclass : inotifypropertychanged { public event propertychangedeventhandler propertychanged; private void firepropertychanged(string propertyname) { var handler = propertychanged; if (handler != null) handler(this, new propertychangedeventargs(propertyname)); } private int sampleintfield; public int sampleintproperty { { return sampleintfield; } set { if (value != sampleintfield) { sampleintfield = value; firepropertychanged("sampleintproperty"); // ouch ! magic string here } } } }
i'd replace one:
using system.runtime.compilerservices; class betterclass : inotifypropertychanged { public event propertychangedeventhandler propertychanged; // check attribute in following line : private void firepropertychanged([callermembername] string propertyname = null) { var handler = propertychanged; if (handler != null) handler(this, new propertychangedeventargs(propertyname)); } private int sampleintfield; public int sampleintproperty { { return sampleintfield; } set { if (value != sampleintfield) { sampleintfield = value; // no "magic string" in following line : firepropertychanged(); } } } }
but read [callermembername]
attribute has poor performances compared alternatives. true , why? use reflection?
no, the use of [callermembername]
not slower upper basic implementation.
this because, according this msdn page,
caller info values emitted literals intermediate language (il) @ compile time
we can check il disassembler (like ilspy) : code "set" operation of property compiled same way :
so no use of reflection here.
(sample compiled vs2013)
Comments
Post a Comment