Equivalent code of CreateObject in C#

If you are using .net 4 or later, and therefore can make use of dynamic, you can do this quite simply. Here’s an example that uses the Excel automation interface.

Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
dynamic ExcelInst = Activator.CreateInstance(ExcelType);
ExcelInst.Visible = true;

If you can’t use dynamic then it’s much more messy.

Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
object ExcelInst = Activator.CreateInstance(ExcelType);
ExcelType.InvokeMember("Visible", BindingFlags.SetProperty, null, 
    ExcelInst, new object[1] {true});

Trying to do very much of that will sap the lifeblood from you.

COM is so much easier if you can use early bound dispatch rather than late bound as shown above. Are you sure you can’t find the right reference for the COM object?

Leave a Comment