Option Strict Off vs On for Late‑Bound COM Members in VB.NET
0 reputation · 25 Dec 2023, 07:22 UTC
0 reputation · 25 Dec 2023, 07:22 UTC
When working with COM interop in VB.NET, developers must choose between Option Strict Off for runtime late binding and Option Strict On for compile‑time safety. Off allows late‑bound member access but risks runtime failures; On enforces type checks but can break existing code.
This creates a concrete constraint: how to maintain compatibility with existing COM libraries while ensuring compile‑time safety. The behavior differs significantly between VB.NET Framework and .NET Core/.NET 5+ regarding late binding resolution order, making migration between compiler versions unpredictable.
Two documented approaches exist:
Which approach provides better long‑term maintainability when targeting both .NET Framework and .NET 6+ deployments with Office COM interop?
31275 reputation · 25 Dec 2023, 11:08 UTC
Enable Option Strict On project‑wide, reference the Office Primary Interop Assemblies (PIAs) via NuGet with EmbedInteropTypes=true, and isolate any unavoidable late‑bound calls in a single file/module that uses Option Strict Off or explicit reflection wrappers. This gives compile‑time safety on both .NET Framework 4.8 and .NET 6+ while keeping the codebase maintainable.
Option Strict Off.Option Strict Off code runs on both platforms.Option Strict On forces early binding; the compiler will error on any member not described in the referenced interop assemblies.EmbedInteropTypes embeds only the types you actually use, reducing deployment size and eliminating version‑specific PIA dependencies.CallByName, My.Computer, dynamic dispatch) compile only when Option Strict Off is in effect for that file/module.Option Strict On at the top of every source file).Microsoft.Office.Interop.* NuGet packages. Verify the project file contains <EmbedInteropTypes>true</EmbedInteropTypes> for each reference.Option Strict Off only there, or wrap the call with explicit reflection/DynamicObject.Does your code call COM members that are not exposed in the Office PIAs (for example, dynamic dispatch to third‑party add‑ins or version‑specific interfaces)? If the answer is yes, you will need the isolated Option Strict Off shim described in step 4; otherwise a pure Option Strict On build is sufficient.
Option Strict On.EmbedInteropTypes is true for all Office interop references.Option Strict Off files are limited to a single, well‑named module (e.g., ComLateBoundShims.vb).Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.