Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ref parameters and reflection

Tags:

c#

reflection

I'm not sure if I'm totally missing something here but I can't find any way to determine if a parameter is passed by reference or not by using reflection.

ArgumentInfo has a property "IsOut", but no "IsRef". How would I go about to get all reference parameters in a given MethodInfo?

like image 203
Patrik Hägne Avatar asked Oct 11 '09 21:10

Patrik Hägne


People also ask

What is a ref parameter?

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.

What are ref and out parameters?

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.

What is the difference between ref & out parameters with example?

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. The ref is a keyword in C# which is used for the passing the arguments by a reference.

What is the method of ref?

The REF method is useful for counting the number of occurrences of each key in a hash object. The REF method initializes the key summary for each key on the first ADD, and then changes the ADD for each subsequent CHECK.


2 Answers

ParameterInfo[] parameters = myMethodInfo.GetParameters(); foreach(ParameterInfo parameter in parameters) {     bool isRef = parameterInfo.ParameterType.IsByRef; } 
like image 63
Rex M Avatar answered Sep 21 '22 17:09

Rex M


ParameterType.IsByRef will return true for both ref and out parameters.

If you have a ParameterInfo object (e.g. from MethodInfo.GetParameters()), then:

  • The param is out if parameterInfo.ParameterType.IsByRef && parameterInfo.IsOut
  • The param is ref if parameterInfo.ParameterType.IsByRef && parameterInfo.IsOut == false

If you don't do the IsByRef check for out parameters, then you'll incorrectly get members decorated with the [Out] attribute from System.Runtime.InteropServices but which aren't actually C# out parameters.

like image 31
RobSiklos Avatar answered Sep 22 '22 17:09

RobSiklos