Monday, June 25, 2012

How to Declare a Value Type Variable

To use a type, you must first declare a symbol as an instance of that type. Value types
have an implicit constructor, so declaring them instantiates the type automatically; you
don’t have to include the New keyword as you do with classes. The constructor assigns
a default value (usually null or 0) to the new instance, but you should always explicitly
initialize the variable within the declaration, as shown in the following code block:

' VB
Dim b As Boolean = False

// C#
bool b = false;

Declare a variable as nullable if you want to be able to determine whether a value has
been assigned. For example, if you are storing data from a yes/no question on a form
and the user did not answer the question, you should store a null value. The following
code declares a boolean variable that can be true, false, or null:

' VB
Dim b As Nullable(Of Boolean) = Nothing

// C#
Nullable// b = null;

// Shorthand notation, only for C#
bool? b = null;

Declaring a variable as nullable enables the HasValue and Value members. Use HasValue
to detect whether a value has been set as follows:

' VB
If b.HasValue Then Console.WriteLine("b is {0}.", b.Value) _
Else Console.WriteLine("b is not set.")

// C#
if (b.HasValue) Console.WriteLine("b is {0}.", b.Value);
else Console.WriteLine("b is not set.");

No comments:

Post a Comment