Note that there are some explanatory texts on larger screens.

plurals
  1. POC#: Initializing an event handler with a dummy
    primarykey
    data
    text
    <p>I've seen this sort of code some places:</p> <pre><code>public event SomeEventHandler SomeEvent = (s, e) =&gt; { }; </code></pre> <p>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?</p> <hr> <p>For example:</p> <pre><code>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)); } </code></pre> <p>Could I change the first line into this:</p> <pre><code>private PropertyChangedEventHandler propertyChanged = (s, e) =&gt; { }; </code></pre> <p>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:</p> <pre><code>protected void OnPropertyChanged(string propertyName) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } </code></pre> <p>Would that be safe when taking the initialization into account? Or are there some side effects I have missed?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload