Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? */);
like image 365
Frank Krueger Avatar asked Feb 21 '10 04:02

Frank Krueger


1 Answers

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; 
    }
}
like image 192
azamsharp Avatar answered Oct 02 '22 14:10

azamsharp