Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use ref types in C# built-in Action<> delegate?

Tags:

c#

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?

like image 577
grigoryvp Avatar asked Nov 10 '09 11:11

grigoryvp


People also ask

Can we use reference in C?

No, it doesn't.

What is ref in C?

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.

Can we use multiple ref in C#?

As per C# Language Specification, returning multiple values from a method is not possible.

When should I use ref?

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.


1 Answers

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); 
like image 138
Jon Skeet Avatar answered Sep 20 '22 01:09

Jon Skeet