I have a piece of code which creates Layers in AutoCAD from an external .NET application.
I use the line GetObject(, "AutoCAD.Application"). The code uses try catch statement to check it has the right object for example. I use AutoCAD.Application for version 2002 and then AutoCAD.Application.15 for the next version and so on.
This has worked until I have run my code with AutoCAD 2007 running. It selects AutoCAD.Application as the running version but when it try's to set it to the object I get an error saying specified cast is not valid.
The class "AutoCAD.Application" is usually set to the last installed version of AutoCAD on any specific system. In your case, you should always use the specific class name for the COM object you are trying to get a reference to. I.E.
"AutoCAD.Application.15" for AutoCAD 2002
"AutoCAD.Application.16" for AutoCAD 2004
"AutoCAD.Application.16.1" for AutoCAD 2005
"AutoCAD.Application.16.2" for AutoCAD 2006
not sure of 2007 though, I don't have it installed right now but it'll be either "AutoCAD.Application.16.3" or "AutoCAD.Application.17"
Again, if you only use "AutoCAD.Application", you will get a reference to whichever version of AutoCAD is registered under that class (which is usually the version which was installed last).
You can check this in the registry (use all appropriate caution when accessing the registry though). It will be under HKEY_CLASSES_ROOT.
Look in the CLSID subkey at the (Default) property. The data will contain the CLSID of the currently registered version, Match that against the CLSID(Default) of the AutoCAD.Application.XXX to find which is current.