1

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
Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
thomasb
  • 5,816
  • 10
  • 57
  • 92

5 Answers5

6

Are you looking for the keyword "Nothing"?

Jon
  • 2,085
  • 2
  • 20
  • 28
  • Hum, actually yes. I see that actually Nothing is equivalent to C# null, while I thought it was only used to see if an object was instantiated. – thomasb Sep 16 '08 at 14:03
2

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#

Luca Molteni
  • 5,230
  • 5
  • 34
  • 42
1
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
gregmac
  • 24,276
  • 10
  • 87
  • 118
0

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
Mark Hurd
  • 10,665
  • 10
  • 68
  • 101
0

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.

Barbaros Alp
  • 6,405
  • 8
  • 47
  • 61