Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does the C# compiler detect COM types?
    primarykey
    data
    text
    <p><strong>EDIT:</strong> I've written the results up as a <a href="http://codeblog.jonskeet.uk/2009/07/07/faking-com-to-fool-the-c-compiler.aspx" rel="noreferrer">blog post</a>.</p> <hr> <p>The C# compiler treats COM types somewhat magically. For instance, this statement looks normal...</p> <pre><code>Word.Application app = new Word.Application(); </code></pre> <p>... until you realise that <code>Application</code> is an interface. Calling a constructor on an interface? Yoiks! This actually gets translated into a call to <a href="http://msdn.microsoft.com/en-us/library/system.type.gettypefromclsid.aspx" rel="noreferrer"><code>Type.GetTypeFromCLSID()</code></a> and another to <a href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx" rel="noreferrer"><code>Activator.CreateInstance</code></a>.</p> <p>Additionally, in C# 4, you can use non-ref arguments for <code>ref</code> parameters, and the compiler just adds a local variable to pass by reference, discarding the results:</p> <pre><code>// FileName parameter is *really* a ref parameter app.ActiveDocument.SaveAs(FileName: "test.doc"); </code></pre> <p>(Yeah, there are a bunch of arguments missing. Aren't optional parameters nice? :)</p> <p>I'm trying to investigate the compiler behaviour, and I'm failing to fake the first part. I can do the second part with no problem:</p> <pre><code>using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [ComImport, GuidAttribute("00012345-0000-0000-0000-000000000011")] public interface Dummy { void Foo(ref int x); } class Test { static void Main() { Dummy dummy = null; dummy.Foo(10); } } </code></pre> <p>I'd like to be able to write:</p> <pre><code>Dummy dummy = new Dummy(); </code></pre> <p>though. Obviously it'll go bang at execution time, but that's okay. I'm just experimenting.</p> <p>The other attributes added by the compiler for linked COM PIAs (<code>CompilerGenerated</code> and <code>TypeIdentifier</code>) don't seem to do the trick... what's the magic sauce?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload