Most of the time when we use MVVM we use the INotifyPropertyChanged interface to provide the notification to the bindings, and the general implementation looks like this:
public class MyClass : INotifyPropertyChanged
{
// properties implementation with RaisePropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
This works fine for me whenever I read the code from the experts - they wrote similar code:
public class MyClass : INotifyPropertyChanged
{
// properties implementation with RaisePropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var tempchanged = PropertyChanged;
if (tempchanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I would like to know what is the exact reason behind creating a temporary object for the PropertyChanged event.
Is it only a good practice or are there any other benefits associated with it?
I have found the answer with Jon's answer and the explained example at:
Understanding C#: Raising events using a temporary variable
Here is the sample code to understand this:
using System;
using System.Collections.Generic;
using System.Threading;
class Plane
{
public event EventHandler Land;
protected void OnLand()
{
if (null != Land)
{
Land(this, null);
}
}
public void LandThePlane()
{
OnLand();
}
}
class Program
{
static void Main(string[] args)
{
Plane p = new Plane();
ParameterizedThreadStart start = new ParameterizedThreadStart(Run);
Thread thread = new Thread(start);
thread.Start(p);
while (true)
{
p.LandThePlane();
}
}
static void Run(object o)
{
Plane p = o as Plane;
while (p != null)
{
p.Land += p_Land;
p.Land -= p_Land;
}
}
static void p_Land(object sender, EventArgs e)
{
return;
}
}