Equivalent code of CreateObject in C#

dralialadin picture dralialadin · Dec 5, 2012 · Viewed 48.7k times · Source

I have a code in VB6. Can anyone tell me how to write it in C#. This code is below:

Set Amibroker = CreateObject("Broker.Application")
Set STOCK = Amibroker.Stocks.Add(ticker)
Set quote = STOCK.Quotations.Add(stInDate)

quote.Open = stInOpen
quote.High = stInHigh
quote.Low = stInlow
quote.Close = stInYcp
quote.Volume = stInVolume


Set STOCK = Nothing
Set quote = Nothing

What is the equivalent of CreateObject in C#?. I try to add references to com object but i can't find any com object as Broker.Application or amibroker

Answer

David Heffernan picture David Heffernan · Dec 5, 2012

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?