Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR & Associates.

Katrin and Jim

Month List

ViewState Property Problems in VB

by Jim Nov 17, 2009 3:50 PM

Quick, what’s wrong with this property? It doesn’t return the value I was expecting.

Public Property ContractIsDeletable() As Boolean
    Get
        If ViewState("ContractDeletable") = Nothing Then
            Return True
        Else
            Return ViewState("ContractDeletable")
        End If
    End Get
    Set(ByVal value As Boolean)
        ViewState("ContractDeletable") = value
    End Set
End Property

Perfectly normal implementation of a ViewState-backed property, right? The following code will print both messages:

ViewState!BooleanCheck = False
If ViewState!BooleanCheck = Nothing Then
    Debug.WriteLine("false is not nothing!!")
End If

ViewState!IntegerCheck = 0
If ViewState!IntegerCheck = Nothing Then
    Debug.WriteLine("zero is not nothing!!")
End If

You can (and I apparently did) get away with the construct at top, if the default value returned in the case of a Nothing happens to be zero, or false. But that evaluation is incorrect. The correct way to make this property is:

    Public Property ContractIsDeletable() As Boolean
        Get
            If IsNothing(ViewState("ContractDeletable")) Then
                Return True
            Else
                Return ViewState("ContractDeletable")
            End If
        End Get
        Set(ByVal value As Boolean)
            ViewState("ContractDeletable") = value
        End Set
    End Property

Because bools and ints aren’t nullable types, the = comparison doesn’t work property. IsNothing does the trick.

Tags:

Code

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading