Late-bound call on Nothing: NullReferenceException or COM dispatch?
0 reputation · 11 Jan 2021, 18:52 UTC
0 reputation · 11 Jan 2021, 18:52 UTC
The Visual Basic language specification does not clearly define whether a late-bound member call on a Nothing reference should immediately raise a NullReferenceException or attempt COM dispatch first. This ambiguity produces different observable outcomes depending on the host environment — .NET Framework, .NET Core/5+, or VBA — and the Option Strict setting.
With Option Strict Off, the compiler permits late-bound calls on Object variables. When that variable holds Nothing, the runtime must decide between throwing a managed NullReferenceException or forwarding the call to the underlying COM layer, which may surface a different error such as a dispatch exception. The specification leaves this decision unresolved, and no compiler flag or runtime switch standardizes the behavior across platforms.
Nothing?35775 reputation · 11 Jan 2021, 23:17 UTC
In standard VB.NET with Option Strict Off, a late-bound member call on a Nothing reference raises a managed NullReferenceException before the binder attempts any dispatch. The runtime binder checks the target for null first; it does not forward a Nothing target to COM dispatch. This is the expected behavior for ordinary .NET objects on .NET Framework and .NET 6+.
Confirmed: Option Strict On rejects late-bound calls at compile time, so the ambiguity appears only with Option Strict Off. Confirmed: a null target cannot expose members, so the managed null exception is the expected result for plain .NET objects.
Likely explanation for COM-dispatch reports: the variable may hold a COM Runtime Callable Wrapper or a COM object reference rather than a true managed Nothing. In that case the binder can reach COM activation and surface a dispatch error. That is a separate case from a managed Nothing reference.
Option Strict Off is enabled in the project or file.Option Strict Off
Module Module1
Sub Main()
Dim target As Object = Nothing
Console.WriteLine(target.ToString())
End Sub
End Module
Observe the exception type. A NullReferenceException means the managed null check ran first. A COM or dispatch error suggests the target was a COM wrapper, not a plain Nothing.
Build and run with the .NET SDK:
dotnet build
dotnet run
Nothing is assigned to a variable typed as a COM class or when an RCW is involved. Treat COM-dispatch reports as requiring a separate reproduction.Was the Nothing variable ever assigned a COM object or RCW? That detail determines whether COM dispatch is in scope.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.