Search code examples
c#.netreflection

How to invoke methods with ref/out params using reflection


Imagine I have the following class:

class Cow {
    public static bool TryParse(string s, out Cow cow) {
        ...
    }
}

Is it possible to call TryParse via reflection? I know the basics:

var type = typeof(Cow);
var tryParse = type.GetMethod("TryParse");

var toParse = "...";

var result = (bool)tryParse.Invoke(null, /* what are the args? */);

Solution

  • You can do something like this:

    static void Main(string[] args)
    {
        var method = typeof (Cow).GetMethod("TryParse");
        var cow = new Cow();           
        var inputParams = new object[] {"cow string", cow};
        method.Invoke(null, inputParams); 
        // out parameter value is then set in inputParams[1]
        Console.WriteLine( inputParams[1] == null ); // outputs True
    }
    
    class Cow
    {
        public static bool TryParse(string s, out Cow cow) 
        {
            cow = null; 
            Console.WriteLine("TryParse is called!");
            return false; 
        }
    }