Either if you migrate your application from VB6 to C# or if you develop a new application in C# something you end up with cases where you need to use your classes in legacy apps. Some of them could have been written in VB6 or could even be VBA macros in Excel applications.
Exposing your .NET classes can be sometimes very easy (you can think is just a matter of putting a ComVisible tag) but in other occasions is not that simple. Specially if your legacy application is using a lot of Late Bound calls like in VBA, so you must make sure that the COM information that you are exposing for your class is exactly what you really want and need.
OK. So I will provide some guidelines or some steps you should follow to provide a consistent COM interface for your .NET Code.
1. First you have to add the [ComVisible(true)] attribute. Don’t think that’s all. Even if in some cases that is enough is better if you take an strict control of want is being generated for your class. Ok Let’s use the following class as an example:
using System;
using System.Runtime.InteropServices;
namespace InteropExamples
{
[ComVisible(true)]
public class MyVerySimpleClass
{
public Class2 CreateANewClass()
{ return new Class2() }
public int GetMyLuckyNumber() { return 15; }
}
public class Class2 {
}
}
// Generated .IDL file (by the OLE/COM Object Viewer)
//
// typelib filename: <could not determine filename>
[
uuid(370E4AD4-073B-4984-8C7D-5ED027F7B1CA),
version(1.0)
]
library ClassLibrary1
{
// TLib : // TLib : mscorlib.dll : {BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}
importlib("mscorlib.tlb");
// TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
importlib("stdole2.tlb");
// Forward declare all types defined in this typelib
interface _MyVerySimpleClass;
[
uuid(E03CCE68-2D55-3576-9DB6-019AAA667A5D),
version(1.0),
custom({0F21F359-AB84-41E8-9A78-36D110E6D2F9}, "InteropExamples.MyVerySimpleClass")
]
coclass MyVerySimpleClass {
[default] interface _MyVerySimpleClass;
interface _Object;
};
[
odl,
uuid(D18BEEE1-4425-3AC7-891E-807EC2283731),
hidden,
dual,
oleautomation,
custom({0F21F359-AB84-41E8-9A78-36D110E6D2F9}, "InteropExamples.MyVerySimpleClass")
]
interface _MyVerySimpleClass : IDispatch {
};
};
In this case your class will be expose using all defaults. That is, a progId that will be the <AssemblyName>.ClassName an interface _<ClassName> is generated and the class is exposed only for IDispatch, which would not provide class information if you add the tlb reference to a VB6 or VBA project.
And if you run this code in VB6 you will have a problem like type mismatch when you try to use the method x.CreateAClass because it is returning an object that is not exposed thru COM.
Private Sub Command1_Click()
Dim x As Object
Set x = CreateObject("InteropExamples.MyVerySimpleClass")
MsgBox x.GetMyLuckyNumber
MsgBox x.CreateAClass
End Sub
So my recommendation is to make explicit what you want to expose. Maybe you only need some of the methods to be exposed. Well that is step two.
2. Define a public, ComVisible(true) interface that will define the methods that you want to be exposed thru COM. Sometimes it is better to implement the interface explicitly. I even recommend using partial classes so you isolate the COM stuff from your normal class. If you class is very simple you can leave all COM stuff there.
//It is better to have an interface, because
//you are completely sure what you are exposing or not
[ComVisible(true)]
public interface _MyVerySimpleClass
{
int GetMyLuckyNumber();
}
3. (Recommedation) This is not an obligatory step but I recommend using partial classes.
//Using partial classes allow you to separate all the
//COM plumbing and leave your .NET implementation simple
public partial class MyVerySimpleClass
{
public Class2 CreateAClass()
{
return new Class2();
}
public int GetMyLuckyNumber() { return 15; }
}
3. Make sure your partial class has the following attributes:
[ComVisible(true)] <—This is obvious because you want to use your class in COM
[ClassInterface(ClassInterfaceType.None)] <—This is because your want to take charge or what will be generated in your Typelib (tlb)
[ComDefaultInterface(typeof(_MyVerySimpleClass))] <—This is to indicate the interface that holds your COM visible methods.
[ProgId("InteropExamples.MyVerySimpleClass")] <—To establish which will be the progId not have a generated one
[Guid("{029D468C-8BE6-498f-8A57-3B4B0306BA41}")] <—this is important specially if you are trying to accomplish binary compatibility
Optionally add this attribute [IDispatchImpl(IDispatchImplType.CompatibleImpl)] this is currently marked as an obsolete attribute but it still works and I have found scenarios, specially in some VBA applications where you need this attribute in order to make some late bound calls.
4. And Explicitly implement the interface methods. This is important because some of the return values or arguments might need convertions. For example what can you do if your method returns a DataSet and your Excel VBA script is expecting something like a Recordset (more on this on other posts).
So now you will have a class like:
//Using partial classes allow you to separate all the
//COM plumbing and leave your .NET implementation simple
public partial class MyVerySimpleClass
{
public Class2 CreateAClass()
{
return new Class2();
}
public int GetMyLuckyNumber() { return 15; }
}
//It is better to have an interface, because
//you are completely sure what you are exposing or not
[ComVisible(true)]
public interface _MyVerySimpleClass
{
int GetMyLuckyNumber();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)] //This is to make sure that no automatic generation of COM methods is done
[ComDefaultInterface(typeof(_MyVerySimpleClass))] //This to explicitly establish which is the default interface
[ProgId("InteropExamples.MyVerySimpleClass")]
[Guid("{029D468C-8BE6-498f-8A57-3B4B0306BA41}")]
[IDispatchImpl(IDispatchImplType.CompatibleImpl)]
partial class MyVerySimpleClass : _MyVerySimpleClass
{
#region _MyVerySimpleClass Members
//Explicit implementation is better because it avoids messing your .NET
//class specification. Sometimes when you expose thru COM you can have problem with
//methods overloads. For example you have to have the same method name but differente
//return type. Or you have a collition with an existing member.
int _MyVerySimpleClass.GetMyLuckyNumber()
{
return GetMyLuckyNumber();
}
#endregion
}
And your TLB is now explicit and exposes ONLY what you really really want.
// Generated .IDL file (by the OLE/COM Object Viewer)
//
// typelib filename: <could not determine filename>
[
uuid(370E4AD4-073B-4984-8C7D-5ED027F7B1CA),
version(1.0)
]
library ClassLibrary1
{
// TLib : // TLib : mscorlib.dll : {BED7F4EA-1A96-11D2-8F08-00A0C9A6186D}
importlib("mscorlib.tlb");
// TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
importlib("stdole2.tlb");
// Forward declare all types defined in this typelib
interface _MyVerySimpleClass;
[
odl,
uuid(80D00C45-EE10-3D65-A5FF-42AB7D8F8A71),
version(1.0),
dual,
oleautomation,
custom({0F21F359-AB84-41E8-9A78-36D110E6D2F9}, "InteropExamples._MyVerySimpleClass")
]
interface _MyVerySimpleClass : IDispatch {
[id(0x60020000)]
HRESULT GetMyLuckyNumber([out, retval] long* pRetVal);
};
[
uuid(029D468C-8BE6-498F-8A57-3B4B0306BA41),
version(1.0),
custom({0F21F359-AB84-41E8-9A78-36D110E6D2F9}, "InteropExamples.MyVerySimpleClass")
]
coclass MyVerySimpleClass {
interface _Object;
[default] interface _MyVerySimpleClass;
};
};
For more info about BinaryCompatibility see my other posts on Interop.