Question

I have a nullable property, and I want to return a null value. How do I do that in VB.NET ?

Currently I use this solution, but I think there might be a better way.

    Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
        Get
            If Current.Request.QueryString("rid") <> "" Then
                Return CInt(Current.Request.QueryString("rid"))
            Else
                Return (New Nullable(Of Integer)).Value
            End If
        End Get
    End Property
Was it helpful?

Solution

Are you looking for the keyword "Nothing"?

OTHER TIPS

Yes, it's Nothing in VB.NET, or null in C#.

The Nullable generic datatype give the compiler the possibility to assign a "Nothing" (or null" value to a value type. Without explicitally writing it, you can't do it.

Nullable Types in C#

Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
    Get
        If Current.Request.QueryString("rid") <> "" Then
            Return CInt(Current.Request.QueryString("rid"))
        Else
            Return Nothing
        End If
    End Get
End Property

Or this is the way i use, to be honest ReSharper has taught me :)

finder.Advisor = ucEstateFinder.Advisor == "-1" ? (long?)null : long.Parse(ucEstateFinder.Advisor);

On the assigning above if i directly assign null to finder.Advisor*(long?)* there would be no problem. But if i try to use if clause i need to cast it like that (long?)null.

Although Nothing can be used, your "existing" code is almost correct; just don't attempt to get the .Value:

Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
    Get
        If Current.Request.QueryString("rid") <> "" Then
            Return CInt(Current.Request.QueryString("rid"))
        Else
            Return New Nullable(Of Integer)
        End If
    End Get
End Property

This then becomes the simplest solution if you happen to want to reduce it to a If expression:

Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer)
    Get
        Return If(Current.Request.QueryString("rid") <> "", _
            CInt(Current.Request.QueryString("rid")), _
            New Nullable(Of Integer))
    End Get
End Property
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top