C# Nullable types

G

Guest

hi,
i'm a new bie to c#.net 2.0....
i've come across a new feature by name nullable types...need some info on it

what is actually a null value...
what exactly is advantage we get by specifying a value type as a null value...

please clarify
 
P

Patrice

For example for a price it would allow to distingusih between something that
is free (0) and something for which don't know the price (null).

It's likely you'll mostly use this for dates (if the vetn occured the date
will be filled, if the event didnt' occured date, the date will be null).
 
K

Kevin Spencer

First of all, a null value is nothing. That is, it indicates that a variable
or reference to data of a given type is unassigned, and therefore has no
value. As for what the advantage is, you have to understand a bit about
reference types and value types to understand nullable types. A reference
type (such as a class) is a type that is referenced by a managed pointer,
and stored in the heap. A value type (such as int, char, and array) is a
type that is referenced directly by its' actual value on the stack. So,
while a pointer can point to nothing, an integer is an allocation of 32 bits
of memory on the stack, and will always have a value, since a bit is either
a 1 or a 0.

However, a value type is actually a class that is treated like a "classic"
value type. So, it is possible to assign a null value (pointer) to a value
type, although it took some additional manipulation of the .Net Framework to
allow this behavior.

There is no advantage necessarily to nullable types, except where they may
be useful. For example, most databases these days allow a null value to be
stored for data in a table, including integers, strings, and dates. It is
helpful, when interacting with a database, to be able to assign a null value
to the variables which interact with the database.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
J

Jon Skeet [C# MVP]

Kevin Spencer said:
First of all, a null value is nothing. That is, it indicates that a variable
or reference to data of a given type is unassigned, and therefore has no
value.

I'd disagree with that - being unassigned is very different to being
assigned the value null. Take:

string x;

string x = null;

(Where x is a local variable.)

In the first case, the variable is unassigned. In the second case, it
is definitely assigned with a value of null, which is the value which
doesn't refer to any object.
 
S

Scott M.

I would have to disagree with your analogy.

If someting is free, it still has a value of zero dollars (as you say), but
if we don't know the price, that doesn't make the price null, it just makes
the price unkown.

null is simply a keyword that indicates that the item in question does not
have a relationship to any data at all.

A = 0 <-- A has a value of zero
A = " " <-- A has a value of the space char
A = "" <-- A has a null value (no data at all)

The benefit of null values is primarially when using databases, since most
databases have tables where not all fields are required to have a value
(like a middle name or apartment number or name suffix, such as Sr. or Jr.).
Since it is possible that a field may be null, we need a way of checking it
as such or passing null values into it.

-Scott
 
J

Jon Skeet [C# MVP]

Scott M. said:
I would have to disagree with your analogy.

If someting is free, it still has a value of zero dollars (as you say), but
if we don't know the price, that doesn't make the price null, it just makes
the price unkown.

null is simply a keyword that indicates that the item in question does not
have a relationship to any data at all.

That much I'd agree with.
A = 0 <-- A has a value of zero
A = " " <-- A has a value of the space char
A = "" <-- A has a null value (no data at all)

That particular example is a bit confusing, as the string literal ""
and null are very different. One is a reference to a 0-length string,
the other is a reference to no object at all.

So I'd say that "" has data - it has the data that it's an empty
string.
 
P

Patrice

Not sure what you meant. How would you mark that the price is unknown if not
using a "nullable" type representing a null value ? As a side note, an empty
string is not a "null" string (in the first case we known that the value is
a zero length string, in the other case we don't know what the value is).

IMO one of the problem in discussing is that null has multiple acceptances.
In the context of a nullable type this is the same than the "NULL" (Il'l use
uppercase for this meaning) marker used in most DB, not the "null"
refererence as usual in C# (likely why MS used HasValue for what is called
"nullable" types toa void the ambiguity). VB.NET uses the Nothing keyword.

Finally I see sometimes what is IMO an abusive use of NULL. If you know that
you have no name suffix, you don't have to use a NULL value but an empty
string will do. You have to use a NULLable column if you want to distinguish
if the value is an empty string or if it has no meaning (i.e. not "known",
"applicable" or whatever semantic you attribute to the NULL value).
 
S

Scott M.

Something having an unknown value is not, in any way, related to a
dissussion of null. The very word you use "unkown" implies that there is,
in fact, something to "know". A null value indicates the exact opposite of
that, that there is no value at all. That's why I said that your alaogy was
not a good one.

When I run into situations where a value is unknown to me, I set up a
variable to capture that value. After doing that, I can then look to see if
the varialbe is null, seven, "green" or anything else. The fact that I
didn't know the value of the variable does not imply null.

You seem to be discussing what a "nullable type" is, rather than the meaning
of "null".
 
K

Kevin Spencer

I'll have to take issue with you here, Jon. Null is not a value technically
speaking, as a value is something. If you declare a string variable without
initializing it, and test it for null, it will return true. While null
doesn't have exactly the same technical meaning that it used to have back in
the days of "simple" C programming, it still signifies nothing, and an
unassigned variable is nothing. You can't make a distinction between nothing
and nothing, and the compiler doesn't either. There are situations in which
the compiler will insist that you assign a null value to a variable, but
those are "safety" checks, and it isn't consistent, as there are other times
when it will not, and will test true for null with an unassigned variable.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
J

Jon Skeet [C# MVP]

Kevin Spencer said:
I'll have to take issue with you here, Jon. Null is not a value technically
speaking, as a value is something. If you declare a string variable without
initializing it, and test it for null, it will return true.

Not if it's a local variable - you'll get a compiler error saying it's
uninitialized. If it's a member variable, it will have the default
*value* of null.

The C# spec agrees with me (2nd edition, section 11.2):

<quote>
The special value null is compatible with all reference types and
indicates the absence of an instance.
While null
doesn't have exactly the same technical meaning that it used to have back in
the days of "simple" C programming, it still signifies nothing, and an
unassigned variable is nothing. You can't make a distinction between nothing
and nothing, and the compiler doesn't either.

You most certainly can. Try compiling the following:

using System;

class Program
{
static void Main(string[] args)
{
string x = null;
Console.WriteLine (x);
}
}

Now take out "= null" and you'll get:

Test.cs(8,28): error CS0165: Use of unassigned local variable 'x'
There are situations in which the compiler will insist that you
assign a null value to a variable, but those are "safety" checks, and
it isn't consistent, as there are other times when it will not, and
will test true for null with an unassigned variable.

Could you give an example where it will test true for null with a
variable which is unassigned in the terminology of the spec? Bear in
mind that instance variables of reference types are considered
"initially assigned variables".
 
J

Jon Skeet [C# MVP]

I'll have to take issue with you here, Jon. Null is not a value technically
speaking, as a value is something. If you declare a string variable without
initializing it, and test it for null, it will return true. While null
doesn't have exactly the same technical meaning that it used to have back in
the days of "simple" C programming, it still signifies nothing, and an
unassigned variable is nothing. You can't make a distinction between nothing
and nothing, and the compiler doesn't either. There are situations in which
the compiler will insist that you assign a null value to a variable, but
those are "safety" checks, and it isn't consistent, as there are other times
when it will not, and will test true for null with an unassigned variable.

Just a few follow-up points I thought of on the way to work:

1) Do you believe that 0 is a real value for an int type? Because
precisely the argument you're using to say that null is the equivalent
of an unassigned value (for reference types) apply to 0 for int
variables - it just happens to be the default value.

2) How do you get around the fact that you can assign the value null
to a variable? Does that make the variable become "unassigned" in your
view? It certainly doesn't in the terminology of any spec I've ever
seen.

3) How about parameter passing - you pass a *value*, whatever that
value is - including null. If null weren't considered a value, the
spec would have to explicitly make mention of it every time the value
of *any* expression were considered.

(Btw, the CLI spec refers to null as a special value too.)

Do you have any evidence from either the CLI spec or the C# spec that
null is *not* a value? "Not a value technically" suggests you've got
some technical source for this statement - could you provide it? I
think the evidence is pretty strong from what I've posted that it
technically *is* a value.

(The above is all talking about reference types. In the context of
nullable types, when you assign the value null in C# to, say, a
Nullable<int> variable, you're still assigning a value, but its
HasValue property will be false.)

Jon
 
P

Patrice

OK I perhaps see a bit better your semantic point. AFAIK some additional
"markers" were suggested in SQL standards to better define various meanings
of "undefined", "unknown"," not applicable" or several other semantics given
to NULL values but never made into products...

I perhaps miss also some nuances as English is not my native language but
hopefull the overall picture should be clear enough for the OP.
 
K

Kevin Spencer

Hi Jon,

Well, it's a bit more complicated than that. If it's a parameter, for
example, the compiler doesn't complain at all. Example:

public boo StringIsNull(string s)
{
return (s == null);
}

Also, note that I said "Null is not a value technically speaking." I
qualified my remark because it depends on what is meant by the term "value."
Of course, null must be represented by a "value" in memory, but it
represents the absence of a value. And as you pointed out, if a member is
declared and not initialized, it is "initialized" as null. But that holds
true for value types as well as reference types. So, what we're seeing here
is more a decision on the part of the designers of the compiler, rather than
a "physical" reality. They could just as easily have assumed a null value
for a local variable, but decided not to.

This is, of course, one of the problems with human language. It is subject
to interpretation. So, in fact, I don't think either of us is wrong about
what we are saying. One or both of us is just not trying hard enough to
understand the other!

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net

Jon Skeet said:
Kevin Spencer said:
I'll have to take issue with you here, Jon. Null is not a value
technically
speaking, as a value is something. If you declare a string variable
without
initializing it, and test it for null, it will return true.

Not if it's a local variable - you'll get a compiler error saying it's
uninitialized. If it's a member variable, it will have the default
*value* of null.

The C# spec agrees with me (2nd edition, section 11.2):

<quote>
The special value null is compatible with all reference types and
indicates the absence of an instance.
While null
doesn't have exactly the same technical meaning that it used to have back
in
the days of "simple" C programming, it still signifies nothing, and an
unassigned variable is nothing. You can't make a distinction between
nothing
and nothing, and the compiler doesn't either.

You most certainly can. Try compiling the following:

using System;

class Program
{
static void Main(string[] args)
{
string x = null;
Console.WriteLine (x);
}
}

Now take out "= null" and you'll get:

Test.cs(8,28): error CS0165: Use of unassigned local variable 'x'
There are situations in which the compiler will insist that you
assign a null value to a variable, but those are "safety" checks, and
it isn't consistent, as there are other times when it will not, and
will test true for null with an unassigned variable.

Could you give an example where it will test true for null with a
variable which is unassigned in the terminology of the spec? Bear in
mind that instance variables of reference types are considered
"initially assigned variables".
 
H

Henning Krause [MVP - Exchange]

Kevin Spencer said:
Hi Jon,

Well, it's a bit more complicated than that. If it's a parameter, for
example, the compiler doesn't complain at all. Example:

public boo StringIsNull(string s)
{
return (s == null);
}

But in this case, you always pass an assigned value to the method. It cannot
be unassigned by definition. Its either null or has reference to something.

This differs from local variables.

Best regards,
Henning Krause
 
K

Kevin Spencer

1) Do you believe that 0 is a real value for an int type? Because
precisely the argument you're using to say that null is the equivalent
of an unassigned value (for reference types) apply to 0 for int
variables - it just happens to be the default value.

Back when I started using C, Kernigan and Ritchie C, that is, which is the
"purest" form, when you declared an integer without assigning it, it didn't
have a value of 0. It had the value of whatever was in the memory location
that the compiler assigned it to. This was because C was not initially
designed to "fix things up" for inexperienced developers.

The fact that the C# compiler assigns a default value to an integer is
something built into the compiler. So, again, we're talking English
semantics here rather than reality. In reality "null" signifies "nothing."
Now, a computer cannot represent nothing without using some number, so 0 (\0
in C) has traditionally been the "value" used to signify nothing, which is
the source of the confusion. Take a look at the dictionary definition of
"null" - http://dictionary.reference.com/search?q=null.

With the advent of higher-level programming languages, more abstraction away
from numbers was added to the mix. For example, in C, 0 is false, and
*anything else* is true. In C, you can write:

while (a + b) { ... }

Logically, this makes perfect sense. Since true is not false, and false is
not true, if 0 is false, what is 2? Since 2 is not 0, it is true. However,
the abstraction introduced by these higher-level languages also muddied the
water. These languages are all compiled to machine language, and therefore
represent mathematical operations. The abstraction proves to be useful, but
at a price, which is confusion. Today, false is not treated as a number by
the developer, and the concepts of true and false have been abstracted to a
higher level which ultimately must be processed numerically by the computer.

The same holds true for "null." The current abstraction level of computing
languages, C# in this discussion, can cause confusion when being talked
about using human language, as the abstractions approximate human ideas. So,
again, we're just having a semantic argument here, which I'm not sure is
useful.

So, I will stand behind my statement that null signifies nothing, which
means that it signifies the absense of a value. One can not signify nothing
with nothing. It must be represented by something. Hence, the confusion.

But, to put it more colloquially, how about trying to understand what I'm
saying, rather than mincing my words? We all have different ways of talking
about things. But it is not the words we use that matter, as much as the
ideas they represent. Human language is not a programming language like C#,
where every token always means exactly the same thing, and there is no room
for interpretation. On the contrary, human language is all about
interpretation, nuance, and gist.

I only hope the OP isn't entirely befuddled by this point! ;-)

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
K

Kevin Spencer

But in this case, you always pass an assigned value to the method. It
cannot be unassigned by definition. Its either null or has reference to
something.

It can be unassigned, if it is a member and not a local variable.

The bottom line (the one that matters, in other words) is that the ideas I
expressed in my original reply were correct, but the words I used to express
them were parsed incorrectly by people for whom the reply was not intended,
for wahtever reason. The OP has not asked for clarification regarding the
reply. I can only hope that this is because the OP understood what I was
saying.

In the end, it doesn't matter which end of the boiled egg one begins at, as
long as one eats the egg.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
S

Scott M.

Hmmm, again, to my knowledge the concepts of "undefined", "unknown"," not
applicable" have never been identified with "null" in SQL or anywhere else.
When I mark a filed in SQL as "nullable", I am not doing it because I don't
know what value the user may want to put into the field. On the contrary, I
do it because I'm letting the user not put any value at all into the field.

Again "undefined", "unknown"," not applicable" does not equal "null". I
think this is super-important to be clear on, because "null" has a special
purpose and meaning and the minute you try to attach a meaning that is
something similiar, but not the same, to it, you confuse the issue and make
it more complicated than it need be.
 
H

Henning Krause [MVP - Exchange]

If it's a member variable, it's assigned the null value at runtime. It's not
unassigned.

Best regards,
Henning Krause
 
P

Patrice

I'm not using null when "I don't know what value the user may want to input"
(actually I never know what value the user will enter, not sure what you
meant).

Also I don't use NULL when "I'm letting the user not put any value at all
into the field" which is IMO bad form at least to do systematically. I'll
use an empty string or 0 as a default value if it makes senses.

I will use this for example for the actual start date of something that not
started yet. In this case you can't provide any value. IMO this is a more
convincing sample than Appartement number and the like where in a real world
scenario you never want to distinguish between a value that can't be
provided for some reason (null) and the fact that the apartment number is
just an empty string because you *know* this is an empty string, not because
you are unable to provide this value.

This is perhaps why I tried at first to explain what's behind null. I felt
that using simply the word "null" was perhaps not sufficient as it is IMO
sometimes misused.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top