Using anonymous event in function

public static void OnAutoScrollToEndChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
    /* ... */

    var scrollToEndHandler = new NotifyCollectionChangedEventHandler((sender, args) => // 수정
    {
        if (listBox.Items.Count > 0)
        {
            object lastItem = listBox.Items[listBox.Items.Count - 1];

            listBoxItems.MoveCurrentTo(lastItem);
            listBox.ScrollIntoView(lastItem);
        }
    });

    if (isAutoScroll)
    {
        source.CollectionChanged += scrollToEndHandler; // A
    }
    else
    {
        source.CollectionChanged -= scrollToEndHandler; //B
    }
}

https://michlg.wordpress.com/2010/01/17/listbox-automatically-scroll-to-bottom/

This code is referenced by upper URL.

A(scrollToEndHandler) and B(scrollToEndHandler) are in a function.

When 'AutoScrollToEndProperty' is changed, 'OnAutoScrollToEndChanged' will be called all the time.

I wondering whether These are same reference. Thanks.

Jon Skeet
people
quotationmark

If your question is basically, "Does unsubscription actually work here?" the answer is C# compiler implementation-specific, theoretically.

On a practical basis, the body of the lambda expression doesn't capture any local variables, but does capture this (by referring to listBox)... so I'd expect the compiler to generate an instance method containing the body of the code in the lambda expression.

If the method is called multiple times on the same target (i.e. this refers to the same object), I'd expect scrollToEndHandler to be a distinct but equal delegate each time - in other words, it would create a new delegate object in each call (which it probably wouldn't if the lambda expression didn't capture anything, and could be implemented as a static method and the delegate cached)... but the event subscription/unsubscription will still work because the delegates are equal (referring to the same target for the same method).

If the lambda expression referred to any local variables in the method, then event handling wouldn't work, because the compiler would capture those local variables via a separate nested class containing the relevant variables and a method for the delegate code, and each method invocation of OnAutoScrollToEndChanged would create a new instance of that nested class, leading to unequal delegates.

As I say though, that's all implementation-specific... it would be better to just move that code into a separate instance method, to make it clearer that it would work.

people

See more on this question at Stackoverflow