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?
Nullable boolean can be null, or having a value “true” or “false”. Before accessing the value, we should verify if the variable is null or not.
The IsNull function returns a Boolean value that indicates whether a specified expression contains no valid data (Null). It returns True if expression is Null; otherwise, it returns False.
Characteristics of Nullable Types The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and != operators with a nullable type.
The Nullable type is an instance of System. Nullable<T> struct. Here T is a type which contains non-nullable value types like integer type, floating-point type, a boolean type, etc. For example, in nullable of integer type you can store values from -2147483648 to 2147483647, or null value.
You can declare a nullable value 3 ways in VB:
Dim ridesBusToWork1? As Boolean
Dim ridesBusToWork2 As Boolean?
Dim ridesBusToWork3 As Nullable(Of Boolean)
Further Reading: MSDN - Nullable Value Types (Visual Basic).
bool?
is just shorthand syntax for a nullable value type: i.e. Nullable<bool>
Boolean?
or Nullable(Of Boolean)
.You can write it like this with a backing property:
Private _willAttend As Nullable(Of Boolean)
Public Property WillAttend As Nullable(Of Boolean)
Get
Return _willAttend
End Get
Set(value As Nullable(Of Boolean))
_willAttend = value
End Set
End Property
Or just use an auto-implemented property like this:
Public Property WillAttend As Boolean?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With