Search code examples
.netvb.netdata-structuresstructure

VB.NET Structs and Nothing - problems


I'm having some headaches using Structures and functions that return Nothing in VB.NET.

Let me try to explain here with this code:

Public Class Form1
    Structure Test
        Dim field1 As String
    End Structure

    Private Function Foo() As Test
        Return Nothing
    End Function

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim st As Test = Foo()
    End Sub
End Class

In the previous code, when I return Nothing as result of Foo function I'd expect that st is Nothing. But this is not what happens.

Then I found in MSDN documentation:

Assigning Nothing to a variable sets it to the default value for its declared type. If that type contains variable members, they are all set to their default values.

So I discovered that when I assign Nothing to a structure, all its members are set to their default values, instead of the struct itself.

Also, I tried to make st a Nullable type by declaring:

    Dim st As Nullable(Of Test) = Foo()  

but, still I can't check if st is Nothing by using:

    If st Is Nothing Then  

or

    If st.Equals(Nothing) Then

So, questions:
1 - Is it possible to assign Nothing to the structure and not to its members?
2 - How can I check if a return struct value is Nothing?


Solution

  • A structure is a value type, it cannot be Nothing. The Nullable type can solve your problem, put a question mark after the type name to make it short and snappy. Here's an example:

    Module Module1
    
        Structure Test
            Dim field1 As String
        End Structure
    
        Private Function Foo() As Test?
            Return Nothing
        End Function
    
        Sub Main()
            Dim st As Test? = Foo()
            Debug.Assert(st is Nothing)
        End Sub
    
    End Module