Novick Software
SQL Server Consulting Design Programming Tuning

  andy novick is a sql server mvp



Tips and Tricks for:  C#, COM

The Problem:   Creating a COM object in .Net based on its ProgID

Once you've created a reference to a COM object on your system, how do you go about creating the object?  You can't just use CreateObject or new.  You have to use a few .Net methods from the System namespace.

Solution: Use GetTypeFromProgID and Activator.CreateInstance.

You can ask for the type using the GetTypeFromProgID method of the Type object.  Then use the static method Activator.CreateInstance to create it from the Type.

The COMCreateObject function is static so I usually include it in my NSLibStatic class.  The sole purpose of the class is to hold static methods that I write.  You can put it anywhere you like.

Then put this method into one of your classes:

/// <summary>
/// Creates a COM object given it's ProgID.
/// </summary>
/// <param name="sProgID">The ProgID to create</param>
/// <returns>The newly created object, or null on failure.</returns>
public static object COMCreateObject (string sProgID)
	// We get the type using just the ProgID
	Type oType = Type.GetTypeFromProgID (sProgID);
	if (oType != null)
		return Activator.CreateInstance(oType);
	return null;

To call it, just supply the ProgID and the object will be instantiated and ready to be used:

    <myobjecttype> myObject = NSLibStatic.COMCreateObject ("myProgID");

I first wrote this function so that I could create an Internet Explorer object.  There's a tip on that one also.


Personal Blog

New Tips:

Use dsinit to set the SQL Server instance for Windows Azure dev storage


Nov 7, '12
Loser: DB

Full Schedule