Question

I was perusing some System classes with ILSpy when I came across this from the System.Internal.HandleCollector class:

internal sealed class HandleCollector
{        
    ... bunch of stuff removed ...

    internal static event HandleChangeEventHandler HandleAdded
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add
        {
            HandleCollector.HandleAdded = (HandleChangeEventHandler)Delegate.Combine(HandleCollector.HandleAdded, value);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove
        {
            HandleCollector.HandleAdded = (HandleChangeEventHandler)Delegate.Remove(HandleCollector.HandleAdded, value);
        }
    }
    ... bunch of stuff removed ...
}

How is it that Microsoft can compile this when VisualStudio complains (I copied the class) that the property doesn't have a setter? Can someone break-down why this works yet my copy of VS complains (build flag?)?

This property does not have a setter

The error is on each of the HandleCollector.HandleAdded = statements.

Was it helpful?

Solution

We don't need to guess what the MS source code is because it is available here.

This is the declaration of HandleAdded from HandleCollector.cs:

internal static event HandleChangeEventHandler HandleAdded; 

It is an auto-implemented event. The problem is with ILSpy's decompilation. Perhaps you should file a bug.

OTHER TIPS

If you want it to compile with an assignment int the add and remove implementations you need to use a field.

Like this:

internal sealed class HandleCollector
{
    private static HandleChangeEventHandler HandleAddedField;

    internal static event HandleChangeEventHandler HandleAdded
    {
        [MethodImpl(MethodImplOptions.Synchronized)]
        add
        {
            HandleCollector.HandleAddedField = (HandleChangeEventHandler)Delegate.Combine(HandleCollector.HandleAddedField, value);
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        remove
        {
            HandleCollector.HandleAddedField = (HandleChangeEventHandler)Delegate.Remove(HandleCollector.HandleAddedField, value);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top