I've seen this sort of code some places:
public event SomeEventHandler SomeEvent = (s, e) => { };
Is that a recommended way of doing things? What does it solve, and does it have any noteworthy side effects? Will I still have to do null checks? Or is that exactly what I don't have to do any more? Will garbage collection still work as it should?
For example:
private PropertyChangedEventHandler propertyChanged;
private readonly object propertyChangedLock = new object();
public event PropertyChangedEventHandler PropertyChanged
{
add
{
lock (propertyChangedLock)
propertyChanged += value;
}
remove
{
lock (propertyChanged)
propertyChanged -= value;
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler;
lock (propertyChangedLock)
handler = propertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
Could I change the first line into this:
private PropertyChangedEventHandler propertyChanged = (s, e) => { };
And then skip the null-check in the OnPropertyChanged method? And if I then skip the null-check could I then also skip the lock? If so that would give me this:
protected void OnPropertyChanged(string propertyName)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
Would that be safe when taking the initialization into account? Or are there some side effects I have missed?