Are event arguments passed by reference or value in C#?

前端 未结 4 1825
栀梦
栀梦 2021-02-19 08:53

A rather simple question (I think), but I don\'t seem to see an answer already. I know that some values are passed via value (like int and long), and others are passed by refer

4条回答
  •  既然无缘
    2021-02-19 09:26

    Arguments themselves are passed by value by default. However, depending on their type, they can be values or references to the actual values you're working with.

    Note that this is not the same as what is commonly known as passing by reference, as the very value actually passed to an argument is copied (i.e. passed by value). However, the effect is similar in that if you change the referenced object within the method, the changes will be visible outside of the method (in the code where you invoked the method), too.

    Now, when passing by value, there is nothing special about event arguments; whether the values are copied or only their references entirely depends on their type. So, as you said, int and long arguments (and some more, any struct types) are value types, while others like string (and any class instances) are reference types.

    Note that a true passing by reference is possible in C#, too, but that requires the ref keyword.

提交回复
热议问题