Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If delegates are immutable, why can I do things like x += y?

Tags:

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)?

like image 623
John Avatar asked Aug 12 '11 17:08

John


People also ask

Why are delegates immutable?

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.

What will happen if a delegate has a non void return type?

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.

What is the real use of delegates in C#?

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.

What does a string is immutable mean?

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.


1 Answers

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.

like image 96
Jon Skeet Avatar answered Jan 04 '23 00:01

Jon Skeet