selectedItem
has two fields:
int? _cost
string _serialNumber
In this example, _cost
and _serialNumber
of selectedItem
are BOTH null. I am reading through the fields of selectedItem
via their properties, and filling in textboxes with their values, when...
TextBox1.Text = selectedItem.Cost.ToString(); //no error
TextBox2.Text = selectedItem.SerialNumber.ToString(); //error
I understand that SerialNumber.ToString()
is redundant (because it is already a string), but I don't understand why this causes this exception:
Nullable object must have a value.
int? _cost is nullable, and does not have a value, yet it does not give me the exception.
string _serialNumber is nullable, and does not have a value, yet it does give me the exception.
This question touches on it, the guy is essentially asking the same thing, but there is no designated answer, and it also doesn't explain why a nullable int
? For example, can I use .ToString()
on a nullable int but not on a null string?
MessageBox.Show
and String.Concat
work with null
strings.
int?
is a value type, which is called Nullable<T>
, that has special handling for null values; string
is a reference type, (though a somewhat odd one) which can actually have a value of null
. An int?
always has a value, it just has a special way of saying "I'm acting like null
right now."
Because string
type's null
really points to nothing, there isn't any object in memory.
But int?
type(nullable) even with value set to null
still points to some object.
If you read Jeffrey Richter's "CLR via C#" you'll find out that nullable type are just facade classes for common types with some incapsulated logics in order to make work with DB null more convenient.
Check msdn to learn about nullable types.
A Nullable<int>
is a struct
and can't really be null. So a method call on a "null" struct still works.
There is some "compiler magic" that makes _cost == null
a valid expression.
null
to Nullable<T>
using ordinary C# code (i.e. operator overloading) would require that you be able to infer a type from the expression "null
", which you can't, as it doesn't have one. The compiler essentially turns Nullable<T> foo = null
into Nullable<T> foo = default(Nullable<T>)
and foo == null
into !foo.HasValue
.
int?
is not actually an object in its own but it's a Nullable<int>
object.
So when you declare int? _Cost
, you are actually declaring Nullable<int> _Cost
and the property of _Cost.Value
is undefined
not the _Cost
object itself.
It is actually a syntactic sugar to use non nullable types like int, bool or decimal easily.
According to MSDN:
The syntax T? is shorthand for System.Nullable
_Cost.Value
is undefined when _Cost
is null (i.e. when _Cost.HasValue
is false)
_Cost
can't really be null
as it isn't a reference type.
A string is a reference type, but a nullable int is a value type. Here is a Good discussion of the differences http://www.albahari.com/valuevsreftypes.aspx.
The Nullable is actually a struct exposing two properties: HasValue and Value. If you do this you will get your error:
int? i = null;
i.Value.ToString()
In order to check whether or not your int? has a value you can access i.HasValue
NullReferenceException
, but an InvalidOperationException
. See Nullable(T).Value.
The reason is simple. int?
or Nullable<int>
is a struct or a value type, it can never be null.
So what happens when we do:
int? _cost = null;
_cost
will have two fields Value
and HasValue
, when we assign null
to _cost
its HasValue
flag will be set to false
and the Value
field would be assigned default(T)
in case of int?
it would 0
.
Now when we call ToString
on _cost
, Nullable<T>
has an override definition of ToString
, which if we look at Microsoft's provided Source Reference is implemented like:
public override string ToString() {
return HasValue ? value.ToString() : "";
}
Thus it returns an empty string, since _cost
is assigned null
.
Now comes the case of string _serialNumber
. Being string
it is a reference type and it can purely hold null
. If it is holding null
then calling ToString
on it would produce the Null Reference Exception as expected.
You may see: Value Types and Reference Types - MSDN
what i think the reason is, when the compiler encounters a primitive data type it wraps it, to its corresponding object. The toString() method call is just an indirect call(wrapping and then calling the method) here and the exception is handled there. While in the case of String, we are directly calling the method. When pointing to a null, the method throws the exception.
TextBox2.Text = selectedItem.SerialNumber.ToString(); //error
yiels error because it's calling function ToString() which is member of System.String. This function returns this instance of System.String; no actual conversion is performed. Also, String is a reference type. A reference type contains a pointer to another memory location that holds the data.
TextBox1.Text = selectedItem.Cost.ToString(); //no error
yields no error because it's calling to function ToString() which is a member of System.Integer. This function converts the numeric value of this instance to its equivalent string representation. Also, Integer is a value type. A data type is a value type if it holds the data within its own memory allocation.
The same function name ToString() but performs different task.
Value types and reference types
Success story sharing
Nullable<T>
type.int?
orInt32?
. NotInt?
selectedItem.Cost.GetType()
will throw ifCost
is null of typeint?
. The difference is thatToString
is a virtual method which is overridden byNullable<T>
and so can be called on theint?
directly. On the other handGetType
is a non-virtual method declared on a base class ofNullable<T>
(onobject
in fact). Therefore the runtime will have to convert theNullable<>
to that class type before it can callGetType
, and that is what is called boxing, butNullable<>
has special boxing rules, so a null reference is produced.