CreateObject equivalent for C#

September 17, 2014 by Anuraj

.Net .Net 4.0 ASP.Net MVC Windows Forms

In current project, I had to use some 3rd party APIs, which is exposed via COM Interop. I found some VB.Net code to consume, but I couldn’t find in C# implementation for the same. Here is the code snippet which is equivalent VB.Net CreateObject method.

var txt = "HelloWorld";
var type = Type.GetTypeFromProgID("vbscript.regexp");
dynamic vbScriptRegEx = Activator.CreateInstance(type);
vbScriptRegEx.Pattern = "l";
Console.WriteLine(vbScriptRegEx.Replace(txt, "##"));

You may get some other errors, if your platform / platform target is different from the COM object compiled platform.

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub