views:

804

answers:

4

I am working through my new MVC book and of course, the samples are all in c# as usual.

There is a line of code that says

public bool? WillAttend { get; set; }

The author explains that the question mark indicates that this is a nullable (tri-state) bool that can be true, false. or null. (A new C# 3 convention.)

Does vb.net support any convention like this. Certainly I can declare a boolean in vb.net and I can explicitly set it to Null (Nothing in vb.net).

What's the difference. IS there more to it in c#. Advantages?

+5  A: 

bool? is just shorthand for Nullable<bool>, and you can use that from VB.Net (Nullable(Of Boolean)).

Private _WillAttend As Nullable(Of Boolean)
Public Property WillAttend() As Nullable(Of Boolean)
    Get
        Return _WillAttend
    End Get
    Set 
        _WillAttend = Value
    End Set
End Property
Joel Coehoorn
Thanks for showing the property declaration too...that would have been the next question.
Seth Spearman
+12  A: 

You can declare a nullable value 3 ways in VB:

Dim ridesBusToWork1? As Boolean
Dim ridesBusToWork2 As Boolean?
Dim ridesBusToWork3 As Nullable(Of Boolean)

Read more on MSDN.

Lucas McCoy
Hey - I never knew you could add the ? after the variable name? Nice! I learned something new today.
BenAlabaster
Thanks for the input
Seth Spearman
@Seth: Thanks for the output. ;-)
Lucas McCoy
A: 

Nullable is used used on value types such as ints, bools and etc which don't support null assignments. This is generally very handy when you methods return integers. If the result of a method is invalid, you can simply return a nullable int set to null instead of a negative integer, which may end up being a valid result in the long run. That's pretty much the only advantage that comes to mind. Others have posted how to do this in VB.NET. I won't go into that.

Sergey
+1  A: 

Nullables are available since .NET 2.0. In that version Microsoft implemented Generics (Nullable is a Generic type). Since .NET 3.0 you are able to use the ? in VB.NET too (previously you were only able to use Nullable(of Boolean)).

So as said by Lucas Aardvark in .NET 3.0 you are able to use 3 declarations of nullables, but in .NET 2.0 only 1 being

Dim myBool as Nullable(of Boolean)
Gertjan