Thursday, April 14, 2011

how to find a reference datatype

public static void Refer(ref int a,ref int b)
in this how do i find that these variables are reference variable programatically ..how do i find their type

From stackoverflow
  • Since C# is strongly typed, you can use any int methods safely since a and b have to be ints. But if you need the Type during runtime, use the typeof operator.

    Type intType = typeof(a);
    
    Andy White : Does typeof work on variables? I was thinking it only worked on type names. I think for variables you have to use a.GetType()
  • Do you mean you want to know via reflection that the method parameters are by-ref?

    You use MethodBase.GetParameters to get the parameters for the method, and then ParameterInfo.ParameterType to find the type of the parameter and Type.IsByRef to check whether or not it's passed by reference.

    Here's a quick example:

    using System;
    using System.Reflection;
    
    public class Test
    {
        public static void Refer(ref int a,ref int b)
        {
        }
    
        static void Main()
        {
            MethodInfo method = typeof(Test).GetMethod("Refer");
            ParameterInfo[] parameters = method.GetParameters();
            foreach (ParameterInfo parameter in parameters)
            {
                Console.WriteLine("{0} is ref? {1}",
                                  parameter.Name,
                                  parameter.ParameterType.IsByRef);
            }
        }
    }
    

    You can't do this in a "strong" way for a variable using a.GetType() or typeof(a) etc. GetType() finds the type of the value of a, which is just an int.

    Cerebrus : Awe...some!! :-)
  • You have the IsByRef property on the parameterInfo.ParameterType.

    MethodInfo refer = typeof(MyClass).GetMethod("Refer");
    ParameterInfo [] parameters = refer.GetParameters();
    foreach (ParameterInfo parameter in parameters)
    {
            Console.WriteLine("Parameter: {0}, Type: {1}, ByRef: {2}", parameter.Name,
            parameter.ParameterType.Name,
            parameter.ParameterType.IsByRef);
    }
    

0 comments:

Post a Comment