11

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? */);
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208

1 Answers1

7

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; 
    }
}
ehiller
  • 1,346
  • 17
  • 32
azamsharp
  • 19,710
  • 36
  • 144
  • 222
  • 9
    Please note that: a) You don't need a 'Cow' instance for Invoking the TryParse method, you can just pass a value of null. b) the parsed 'Cow' is returned in inputParams[1], the 'cow' in the code above remains unchanged. – Lukas Pokorny Feb 21 '10 at 12:28
  • And therefore this was the answer, +1 all round. – Matt Sach Oct 18 '13 at 12:15