Unless you use On Error Resume Next
and there is an exception in the MyClass
constructor, or you create a proxy that returns Nothing
on creation.
While confirming the VB.NET version of the proxy "works", I noticed myObj Is Nothing
is False
immediately after creation (like you've asked for in the OP), and yet when you try to do anything else with it, it certainly looks like Nothing
. And it normally becomes Nothing
once you've tried to do much more with it than test it for a value. (At this stage it's the same with C#. And at this point I should really start a new question...)
But I've found that the presence of an "empty" Try Catch
is enough for VB.NET to crystallise the Nothing
! (As of the Roslyn C# 6 (Beta) version of LinqPad, C# performs the same.)
Sub Main()
Dim myObj = New MyFunnyType()
If myObj Is Nothing Then
Call "It IS Nothing".Dump
Else
' Comment out this Try and myObj will not be Nothing below.
Try
'Call myObj.ToString.Dump
Catch nr As NullReferenceException
Call "Maybe it was nothing?".Dump
Catch ex As Exception
Call ex.Message.Dump
End Try
Call myObj.Dump("Nil?")
If myObj Is Nothing Then
Call "Now it IS Nothing".Dump
Else
Call "It still is NOT Nothing!".Dump
End If
End If
End Sub
' Define other methods and classes here
Class MyFunnyProxyAttribute
Inherits ProxyAttribute
Public Overrides Function CreateInstance(ByVal ServerType As Type) As MarshalByRefObject
Return Nothing
End Function
End Class
<MyFunnyProxy> _
Class MyFunnyType
Inherits ContextBoundObject
Public Overrides Function ToString() As String
If Me IsNot Nothing Then
Return "Yes, I'm here!"
Else
Return "No, I'm really Nothing!"
End If
End Function
End Class
Note the call to ToString
is meant to be commented out: when it is not the Nothing
is crystallised as 'expected'.
(Until the Roslyn C# 6-based LinqPad I didn't see a similar effect in C#. I.e. just commenting out the ToString
call within the try
was enough for myObj
to remain non-null
. The C# 6 LinqPad (Beta) performs the same as VB.NET, requiring the try
to be removed to not have the null
crystallised.)