Error 'Unable to cast object of type 'System.RuntimeType' to type 'EnvDTE80.DTE2'

777 views Asked by At

I am attempting to mimic what is done here. I have added all the required references and using the same version of VS (2017) as in the example, with the same line of code. When attempting to run the following line of code:

EnvDTE80.DTE2 dte = System.Type.GetTypeFromProgID("VisualStudio.DTE.15.0");

There is the error, "Cannot implicitly convert type 'System.Type' to 'EnvDTE80.DTE2'.

Ok, so then I try this,

EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)System.Type.GetTypeFromProgID("VisualStudio.DTE.15.0");

Then there is this error when running the code, "Unable to cast object of type 'System.RuntimeType' to type 'EnvDTE80.DTE2'

Could somebody please help? My guess is that it is something very simple since I am new to C#.

Thank you very much!

1

There are 1 answers

0
Jakob On BEST ANSWER

The author of the webpage you linked to here :-P

Do this:

Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.15.0");
EnvDTE80.DTE2 dte = (EnvDTE80.DTE2)System.Activator.CreateInstance(type);

For more recent examples of how the DTE and the TwinCAT automation interface is used you can look at either one of these two projects: