Skip to content

Embedded interop types C# 4.0type safetyinterop

Embed COM interop type information directly into assemblies.

When referencing COM types in your C# application previously it would look for the Primary Interop Assembly (PIA) at runtime.

This was problematic as PIAs are often missing or overwritten, yet they were required so that two different assemblies would treat the same COM object as the same type.

C# 4.0 added a new /link compiler switch (<EmbedInteropTypes>true</EmbedInteropTypes> on the reference in a project file) that embeds just the interop types you use at compile time, so they do not need to be independently deployed. .NET 4 also added type equivalence, so embedded copies of the same COM type in different assemblies (matched by GUID or TypeIdentifier, not by structure) are treated as the same type.

Code ​

csharp
// Interop types are embedded at compile time, so no PIA is needed at runtime
var app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
Workbook workbook = app.Workbooks.Add();
csharp
// Required the Primary Interop Assembly (PIA) to be present at runtime
// Missing or mismatched PIAs caused runtime failures
var app = new Microsoft.Office.Interop.Excel.ApplicationClass();
app.Visible = true;
Workbook workbook = app.Workbooks.Add(Type.Missing);

Notes ​

  • Embedding is a project or compiler setting, so the code itself barely changes
  • Calling Add() without Type.Missing comes from C# 4.0's support for Optional arguments C# 4.0 on COM methods, not from embedding
  • Classes such as ApplicationClass cannot be embedded; use the interface (Application) instead
  • With embedded types, COM members typed as object are exposed as dynamic C# 4.0, avoiding many casts

More information ​

Powered by Intracia