Wednesday, November 3, 2010

Test if Integer has been set : Nullable Value Types

For example, let's say that you have an integer for tracking some value and it can be positive and negative.
It is also possible for the value to be not set yet.
How do you detect that the value hasn't been set yet?
You typically come up with some arbitrary number like 99999999 and hope that the real value is never actually 999999999.

A better way since .NET 2.0, Nullable Value Types
Class [MyClass]
 
Private someValue As System.Nullable(Of Integer)
    Public Sub New()someValue = Nothing
End Sub
 
Public Function GetSomeValue() As Integer
    If someValue IsNot Nothing Then
        Return someValue
    Else
        Throw New Exception("Some Value has not been set")
    End If
End Function
 
End Class

This is a much cleaner and safer way than checking for some arbitrary number like 999999999.

Following snippet from Microsoft explains :
http://msdn.microsoft.com/en-us/library/ms235245(v=VS.100).aspx




So what are Nullable Value Types ?




Sometimes you work with a value type that does not have a defined value in certain circumstances.
For example, a field in a database might have to distinguish between having an assigned value
that is meaningful and not having an assigned value.
Value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.

Each nullable type is constructed from the generic Nullable(Of T) structure.
Consider a database that tracks work-related activities.
The following example constructs a nullable Boolean type and declares a variable of that type.
You can write the declaration in three ways:


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

The variable ridesBusToWork can hold a value of True, a value of False, or no value at all. Its initial default value is no value at all, which in this case could mean that the information has not yet been obtained for this person. In contrast, False could mean that the information has been obtained and the person does not ride the bus to work.

You can declare variables and properties with nullable types, and you can declare an array with elements of a nullable type.
You can declare procedures with nullable types as parameters, and you can return a nullable type from a Function procedure.

You cannot construct a nullable type on a reference type such as an array, a String, or a class.
The underlying type must be a value type. For more information, see Data Type Implementation (Visual Basic).

 



How to Use a Nullable Type Variable?




The most important members of a nullable type are its HasValue and Value properties.
For a variable of a nullable type, HasValue tells you whether the variable contains a defined value.
If HasValue is True, you can read the value from Value.
Note that both HasValue and Value are ReadOnly properties.


Default Values
When you declare a variable with a nullable type, its HasValue property has a default value of False. This means that by default the variable has no defined value, instead of the default value of its underlying value type. In the following example, the variable numberOfChildreninitially has no defined value, even though the default value of the Integer type is 0.



Dim numberOfChildren? As Integer

A null value is useful to indicate an undefined or unknown value.
If numberOfChildren had been declared as Integer, there would be no value that could indicate that the information is not currently available.


Storing Values

You store a value in a variable or property of a nullable type in the typical way. The following example assigns a value to the variable numberOfChildren declared in the previous example.


numberOfChildren = 2

If a variable or property of a nullable type contains a defined value, you can cause it to revert to its initial state of not having a value assigned. You do this by setting the variable or property to Nothing, as the following example shows.


numberOfChildren = Nothing

Note

Although you can assign Nothing to a variable of a nullable type, you cannot test it for Nothing by using the equal sign.
Comparison that uses the equal sign, someVar = Nothing, always evaluates to Nothing.
You can test the variable's
HasValue property for False, or test by using the Is or IsNot operator.


Retrieving Values
To retrieve the value of a variable of a nullable type, you should first test its HasValue property to confirm that it has a value.
If you try to read the value when HasValue is False, Visual Basic throws an InvalidOperationException exception.
The following example shows the recommended way to read the variable numberOfChildren of the previous examples.


If numberOfChildren.HasValue Then
    MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
    MsgBox("It is not known how many children there are.")
End If

A database is one of the most important places to use nullable types.
Not all database objects currently support nullable types, but the designer-generated table adapters do.
See "TableAdapter Support for Nullable Types" in TableAdapter Overview.


See Also


Tasks
Troubleshooting Data Types (Visual Basic)

Reference
InvalidOperationException
If Operator (Visual Basic)
Is Operator (Visual Basic)
IsNot Operator (Visual Basic)
HasValue

Concepts
Data Types in Visual Basic
TableAdapter Overview
Local Type Inference (Visual Basic)
Other Resources
Data Type Implementation (Visual Basic)

techPhile: Using VB keywords as Variables

techPhile: Using VB keywords as Variables

Credits goto : Cody Schouten


Using VB keywords as Variables

In C#, a name of a get/set accessor was not a keyword but in VB.Net it was. No matter what libraries or how many different online code converters I tried, I could not get it to work. I finally resorted to google and found out that you can surround a keyword with brackets ([ ]) and than you can use that keyword however you need. In my case it allowed me to use custom sinks in .NET Remoting. Here's an example:

Dim [New] as String
New = "Blah"

As a very BIG note: Be careful when using it. When you can name something other than a reserved keyword, do so. It can cause many issues if you use this unwisely.