x


Why doesn't unregistering an anonymous delegate trigger an error?

If you test it, you will see that it doesn't do anything. Why is it even permitted?

using UnityEngine;

public class LogItInAwake : MonoBehaviour {

delegate void EventHandler ();
EventHandler LogIt;

void Awake () {
    LogIt += () => Debug.Log("It");
    LogIt -= () => Debug.Log("It");
    LogIt();
}

}
more ▼

asked Sep 23 '10 at 12:59 AM

Jessy gravatar image

Jessy
15.6k 72 95 196

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You can unregister any delegate without getting an error, whether it is named or not or registered or not. (Why, I don't know, possibly for efficiency reasons or simply because it is not required by the C# standard).

By holding a reference to the delegate, you can successfully unregister it:

using UnityEngine;

public class LogItInAwake : MonoBehaviour
{    
    delegate void EventHandler();
    EventHandler LogIt;

    void Awake()
    {
        EventHandler x = () => Debug.Log("It");

        LogIt += x;
        LogIt -= x;

        LogIt();
    }    
}

Some more info:

more ▼

answered Sep 23 '10 at 09:35 AM

Herman Tulleken gravatar image

Herman Tulleken
1.6k 25 36 56

That's good info, and I didn't know that, so thank you, but as you said, you don't have an answer to the question.

Sep 25 '10 at 01:36 PM Jessy
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x166
x31
x6

asked: Sep 23 '10 at 12:59 AM

Seen: 962 times

Last Updated: Sep 23 '10 at 12:59 AM