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

前端 未结 4 1840
栀梦
栀梦 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:43

    I know that some values are passed via value (like int and long), and others are passed by reference (like Strings) when you pass them to functions.

    Nope. By default everything is passed by value - but when you're using reference types, the "everything" is a reference. That reference is passed by value. That's not the same as pass by reference. See my article on parameter passing for more details.

    Event arguments are exactly the same - any references are passed by value, assuming the corresponding delegate doesn't use out or ref parameters.

    EDIT: So to address your concern: yes, if your event argument is mutable and you're going to act on a different thread, you should create a copy first... or alternatively, pass the existing reference and then create a new (empty) list in your worker thread.

提交回复
热议问题