COM Interop – Which Is Better for COM Interop Support: C# or VB.NET?

ccomvb.net

I keep hearing that c# is "better" than vb… but as far as I can see, aside from syntactical differences, both compile down to the same IL. I've found some good articles by googling that explain what the differences are between the two and so I feel comfortable in "diffusing" conversations between developers arguing over vb / c#.
=)

But I did read an article that said vb.net 2005 had better support for com interop stuff. But i'm wondering if this is still the case? This is of interest to me because we are in the middle of redesigning an old vb6 app that communicates with some older COM components.

Does anyone have recent experience with .NET and COM interop?
Thanks.

Best Answer

Before .NET 4.0, VB.NET had a slight advantage over C# when calling COM interop code. This was especially true for code, such as the Office programmability model which, as mortalapeman notes, makes use of COM's support for optional parameters. This API often exposed methods with 10, 15 or more parameters (ugh!), all of which were ref params, which in C# had to be specified as references to Missing.Value. This was a pain.

It's important to note, though, that while this was common when calling Office code, I never really encountered it anywhere else. Most COM APIs I worked with were a lot more straightforward, and could be called from C# with little hassle.

However, in .NET 4.0, even this small problem has been corrected. For general purpose COM APIs, you can use the dynamic keyword to call late-bound code without the strong type checking C# usually demands, and thus call COM APIs without a hitch. Check out this article on general usages of dynamic, and this one specifically for working with COM objects.

If you're planning on using this to interop with Office components, C# 4.0 offers an even simpler solution. Check out this MSDN article on Office's optional parameters:

Visual C# enables you to omit optional ref parameters only for methods of interfaces, not classes.

[...]

If you want to write code that omits optional ref parameters of a method in the ThisDocument class, you can alternatively call the same method on the Microsoft.Office.Interop.Word.Document object returned by the InnerObject property, and omit the parameters from that method. You can do this because Microsoft.Office.Interop.Word.Document is an interface, rather than a class.

So instead of calling myWordDoc.CheckSpelling() with 12 (count'em, 12!) pointless optional parameters, you can call myWordDoc.InnerObject.CheckSpelling(IgnoreUpperCase: true), clean and neat.

Related Topic