On Jun 15, 10:50*am, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
Tony Johansson <johansson.anders...@telia.comwrote:
I'm reading in a book called *Visual C# 2005. In the chapter about Generics
there ia a section about Nullable types.
Here is the text that isn't complete true I think. It says:
"You can also look at the value of a reference type using the Value
property. If HasValue is true, then
*you are guarantee a non-null value for Value, but if HasValue is false,
that is, null has been assigned to the variable, then accessing Value will
result in an exception of type System.InvalidOperationException."
Here it says reference type but this is wrong because it's a value type like
the normal primitive types like int, double and also struct is a value type.
For example int? *intNullable = null;
Here the variable intNullable is a value not a reference type like they are
claiming in the text.
Do you agree with me here?
Yes. Which book is it? I suggest you try to find an errata page for the
book - it may already be listed, and if it isn't you should contact the
author so they can correct it for a future printing.
It isn't exactly "wrong". You can set a reference variable to be null,
as
we all know:
bool? bValue = null;
if (bValue.HasValue)
{
Console.WriteLine("Reference is not null");
}
int? iValue = null;
if (iValue.HasValue)
{
Console.WriteLine("Reference is not null");
}
Works fine. The problem is probably the text surrounding the block the
OP
gave us. For example, from the microsoft site, we have:
Using Nullable Types (C# Programming Guide)
Nullable types can represent all the values of an underlying type, and
an additional null value. Nullable types are declared in one of two
ways:
System.Nullable<Tvariable
-or-
T? variable
T is the underlying type of the nullable type. T can be any value type
including struct; it cannot be a reference type.
For an example of when you might use a nullable type, consider how an
ordinary Boolean variable can have two values: true and false. There
is no value that signifies "undefined". In many programming
applications, most notably database interactions, variables can exist
in an undefined state. For example, a field in a database may contain
the values true or false, but it may also contain no value at all.
Similarly, *reference types* can be set to null to indicate that they
are not initialized.
This disparity can create extra programming work, with additional
variables used to store state information, the use of special values,
and so on. The nullable type modifier enables C# to create value-type
variables that indicate an undefined value.
***************
My emphasis above between the * and * in the quoted text. The book is
*probably* wrong, but not certainly
so. I'd want to see the whole page before I cast aspersions.
Matt