2

I read that delegate are immutable objects.

If I have into a thread:

EventHandler handler = (s, e) => Console.WriteLine("...");
EventHandler copy = handler;
copy(new object(), EventArgs.Empty);

that copy is a thread safety operations so when I invoke copy(...) if another thread eliminated the delegate from handler no exception can raise.

However If I make, i.e,:

handler.GetHashCode() and copy.GetHashCode() they both returns the same code.

I thought that the assignment operator did a new instance of that delegate and that the new reference had put into copy variable...

How can, thus, copy and handler be independent if they both references the same object in memory?

Confused!

xdevel2000
  • 20,780
  • 41
  • 129
  • 196
  • You actual question seems to be _"does an equal hashcode mean both variables refer to the same instance"_, to which the answer is "no". – CodeCaster Apr 04 '16 at 12:34
  • 2
    @CodeCaster However in this case both variables do reference the same object. – juharr Apr 04 '16 at 12:35
  • 1
    Immutable means you cannot change the object. You can however assign a new object to `handler` (or even set it to null) and that change will not effect `copy`. – juharr Apr 04 '16 at 12:37
  • 2
    @CodeCaster, my question is on delegate immutability and assignment operator and not on exact meaning of GetHashCode. – xdevel2000 Apr 04 '16 at 12:41
  • 3
    @xdevel your wording: _"handler.GetHashCode() and copy.GetHashCode() they both returns the same code"_ and _"How can, thus, copy and handler be independent if they both references the same object in memory"_ makes it very clear that you think _"equal hash code means same object in memory"_, but whatever. – CodeCaster Apr 04 '16 at 12:53

1 Answers1

2

I thought that the assignment operator did a new instance of that delegate and that the new reference had put into copy variable...

No, it doesn't create a new instance. It assigns the current instance, so if another thread changes the registered delegates on the event, the current instance is remained the same. Since the event handler is immutable, the assignment on the event handler will result in a new object.

As a side note: strings are immutable too, but assigning one string to another doesn't copy it, aka 'makes a new instance'.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • So after the copy, if a thread remove on `handler` the referencing delegate with `-=` operator, it is using, actually, the `Remove` method that creates a new `Delegate` that not contains the delegate passed as argument. So also if `copy` point to the same delegate the method is still there... – xdevel2000 Apr 04 '16 at 12:55
  • Yes, it is. @xdevel2000 – Patrick Hofman Apr 04 '16 at 12:55