C# has built-in delegates Action<>
and Func<>
. Is it possible to use 'ref' type parameters for this delegates? For example, this code:
public delegate void DTest( ref Guid a ); public event DTest ETest;
Will compile. But if I use Action<>
, it will not compile:
public event Action< ref Guid > ETest;
Any hints?
No, it doesn't.
The ref keyword indicates that a value is passed by reference. It is used in four different contexts: In a method signature and in a method call, to pass an argument to a method by reference. For more information, see Passing an argument by reference. In a method signature, to return a value to the caller by reference.
As per C# Language Specification, returning multiple values from a method is not possible.
ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.
No, you can't use pass-by-reference with the Action
delegates. While there is a concept of "type passed by reference" as a Type
in the framework, it's not really a type in the normal sense as far as C# is concerned. ref
is a modifier for the parameter, not part of the type name, if you see what I mean.
However, you can build your own set of equivalent types, e.g.
delegate void ActionRef<T>(ref T item);
Of course, if you want a mixture of ref and non-ref parameters in the same delegate, you get into a horrible set of combinations:
delegate void ActionRef1<T1, T2>(ref T1 arg1, T2 arg2); delegate void ActionRef2<T1, T2>(T1 arg1, ref T2 arg2); delegate void ActionRef3<T1, T2>(ref T1 arg1, ref T2 arg2);
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