Net Core reflection, detect input parameter from ParameterInfo

Jan Barnet 1 Reputation point
2021-02-12T14:54:42.413+00:00

Hello, I am developer using Visual studio for platform net core. I am testing the example on your site, copy paste from here : "https://learn.microsoft.com/en-us/dotnet/api/system.reflection.parameterinfo.attributes?view=net-5.0" . I am using the net core app 3.1 sdk & runtime. I am not able to find out why the first argument of MyMethod is not reflected as IN in attributes by the net reflection mechanism. And how to find out it by another way if exists? Thank you, Jan

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,156 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sreeju Nair 12,346 Reputation points
    2021-10-06T07:35:34.047+00:00

    As per the documentation from the following URL

    https://learn.microsoft.com/en-us/dotnet/api/system.reflection.parameterinfo.attributes?view=net-5.0

    To get the ParameterAttributes value, first get the Type. From the Type, get the ParameterInfo array. The ParameterAttributes value is within the array.
    These enumerator values are dependent on optional metadata. Not all attributes are available from all compilers. See the appropriate compiler instructions to determine which enumerated values are available.

    For you to check whether a parameter is In or Out, you can use the IsOut property and decide.

    e.g.

     internal class Program  
            {  
                static void Main(string[] args)  
                {  
                    Console.WriteLine("Hello World!");  
                    Type myType = typeof(MyClass1);  
                    MethodBase myMethodBase = myType.GetMethod("MyMethod");  
                    ParameterInfo[] myParameters = myMethodBase.GetParameters();  
                    Console.WriteLine("\nThe method {0} has the {1} parameters :",  
                                  "ParameterInfo_Example.MyMethod", myParameters.Length);  
                    for (int i = 0; i < myParameters.Length; i++)  
                    {  
                          
                        Console.WriteLine("\tThe {0} parameter is {1}",  
                                                            i + 1, myParameters[i].IsOut?"Out":"In");  
                    }  
                }  
            }  
          
          
            public class MyClass1  
            {  
                public int MyMethod(int i, out short j, ref long k)  
                {  
                    j = 2;  
                    return 0;  
                }  
            }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.