Reading C# In Depth, 2nd edition, section 2.1.2 on combining and removing delegates.
The subsection title states that "delegates are immutable" and that "nothing about them can be changed." In the next paragraph, though, it talks about using constructs like
x += y;
where x
and y
are variables of compatible delegate types.
Didn't I just change x
? Or does the immutability part deal with when x
is disposed of when I do this (i.e., immediately)?
By making it immutable, the delegate object cannot get corrupted since it always sets fields on an object that nobody has a reference to yet. Reassigning the delegate object reference is atomic, a basic . NET memory model guarantee. So no need for a lock anymore.
When the return type is not void as above in my case it is int. Methods with Int return types are added to the delegate instance and will be executed as per the addition sequence but the variable that is holding the return type value will have the value return from the method that is executed at the end.
Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
Immutable means that which cannot be changed or modified. So when you assign a value to a string, this value is created from scratch as opposed to being replaced. So everytime a new value is assigned to the same string, a copy is created. So in reality, you are never changing the original value.
That's like doing:
string x = "x"; string y = "y"; x += y;
Strings are immutable too. The code above not changing the string objects - it's setting x
to a different value.
You need to differentiate between variables and objects. If a type is immutable, that means that you can't change the data within an instance of that type after it's been constructed. You can give a variable of that type a different value though.
If you understand how that works with strings, exactly the same thing is true with delegates. The += actually called Delegate.Combine, so this:
x += y;
is equivalent to:
x = Delegate.Combine(x, y);
It doesn't change anything about the delegate object that x
previously referred to - it just creates a new delegate object and assigns x
a value which refers to that new delegate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With