2
class Device{
    private object device;
    public Device(string ProgID)
    {
        if (ProgID == "") ProgID = "ScopeSim.Telescope";
        device = Activator.CreateInstance(Type.GetTypeFromProgID(ProgID));
        Console.WriteLine("Connected");
    }
    public object Invoke(string Name, object[] args)
    {
        var v1 = device.GetType(); //this is a com object in debug
        var v2 = v1.GetMethod(Name);
        var v3 = v2.Invoke(device,args); //throws exception, v2 is null
        return v3;
    }
}
//somwhere else in another method in another class that has this in a field...
Console.WriteLine(new Device("").Invoke("A Method Name that is a string but is not known and could be anything, for testing, the name is 'Unpark'", object[] args));

This throws a NullReferenceException. The Unpark method does exist but it does not have a return type, but it does exist. Also, when it stopped to debug (on the exception) the ProgID field in the constructor was null. I would assume that this is normal though, right? It would have already run. Does anyone know why it throws it? If I declare device as dynamic, says it can't bind at runtime to a null object (basically the same thing).

Response to First Answer: I think reflection requires the variables as an array of objects. Yes, Unpark is written with a capital U. The ProgID thing apparently seems to be irrelevant.

Arlen Beiler
  • 15,336
  • 34
  • 92
  • 135
  • you mean like `device.InvokeMethod(Name);`? Oh hum, I did it again. The method name is not known at compile time. – Arlen Beiler Oct 23 '12 at 16:03
  • What I mean is that I don't even know what methods will be called at compile time. The only reason I know it now is for testing. I have an interface which the device is required to implement, but that is only relevant for testing, the program couldn't care less as long as it exists. – Arlen Beiler Oct 23 '12 at 16:14

2 Answers2

0

Well, if ProgID is null, it won't be set, as you only check if the string is empty. I always use string.IsNullOrEmpty(s) instead of s == "".

Check this:

  • Is the Unpark Method really written with a capital U?
  • Does it require the object[] argument?
Peter Stock
  • 301
  • 1
  • 7
0

Well, I think I finally figured it out, thanks to this answer: https://stackoverflow.com/a/3199919/258482. The problem is that you have to use InvokeMember to do anything to a COM object.

Community
  • 1
  • 1
Arlen Beiler
  • 15,336
  • 34
  • 92
  • 135
  • 1
    Though a fine answer at the time, c# 4 makes it much easier to perform COM-interop via the `dynamic` keyword so there is no need for `InvokeMember`. See my answer on that link –  Feb 07 '15 at 00:14