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.

2
  • you mean like device.InvokeMethod(Name);? Oh hum, I did it again. The method name is not known at compile time. Commented Oct 23, 2012 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. Commented Oct 23, 2012 at 16:14

2 Answers 2

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?
Sign up to request clarification or add additional context in comments.

1 Comment

I think it is reflection that requires those objects.
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.