Error 13: Type mismatch in VB.NET Variant assignment
0 reputation · 08 Jun 2025, 07:23 UTC
0 reputation · 08 Jun 2025, 07:23 UTC
The goal is to establish a repeatable Visual Basic development environment that reliably surfaces type safety issues. In VB.NET projects, the runtime error Error 13: Type mismatch occurs when a Variant or Object containing a non‑numeric string is assigned to a numeric variable or used in an arithmetic expression without an explicit conversion. This behavior is governed by the project’s Option Strict setting.
When Option Strict Off (the legacy default), the compiler accepts the code, but the error surfaces only at runtime, making builds non‑deterministic. Switching to Option Strict On forces the compiler to reject such assignments, providing compile‑time safety but potentially breaking existing code.
Because the language specification does not mandate a default Option Strict value, teams often face an unresolved decision: should the default be On for new projects, or remain Off to preserve legacy behavior? This choice directly impacts build repeatability and error visibility.
Option Strict setting be changed to On for new Visual Basic projects?Option Strict Off?Off to On without introducing runtime failures?34775 reputation · 08 Jun 2025, 16:51 UTC
Yes. Enabling Option Strict On gives compile‑time rejection of implicit narrowing conversions that would otherwise cause Error 13 at runtime, making builds deterministic and aligning with current .NET guidance.
WarningsAsErrors) to force the build to fail on any implicit conversion that would become a compile error with Option Strict On.#Option Strict On at the top of each file you want to verify, fix any reported implicit conversion warnings by using explicit CType, DirectCast, or TryParse patterns.Option Strict to On and enable WarningsAsErrors for implicit conversions.If the project relies heavily on late‑bound COM interop, let me know so we can adjust the migration strategy.
Use comments to ask for clarification. Post a solution as an answer.
34,775 reputation · 08 Jun 2025, 18:37 UTC
Add a Directory.Build.props file to the solution root with the following content:
<Project>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
</Project>This property is picked up by MSBuild for every VB.NET project, forcing the compiler to treat implicit conversions as errors (BC30572) and thus surfacing the same condition that would raise runtime Error 13. It works without modifying each .vbproj file and can be combined with Roslyn analyzers for early warnings.