Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?

C#StringNullIntNullable

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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<T>, where T is a value type. The two forms are interchangeable.

Solution 4 - C#

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

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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.

Solution 8 - C#

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.

String.ToString Method

Int32.ToString Method

Value types and reference types

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCptSupermrktView Question on Stackoverflow
Solution 1 - C#Johnny_DView Answer on Stackoverflow
Solution 2 - C#Hans KestingView Answer on Stackoverflow
Solution 3 - C#Asif MushtaqView Answer on Stackoverflow
Solution 4 - C#Corné HogerheijdeView Answer on Stackoverflow
Solution 5 - C#Tom HighfieldView Answer on Stackoverflow
Solution 6 - C#HabibView Answer on Stackoverflow
Solution 7 - C#Sashi KantView Answer on Stackoverflow
Solution 8 - C#TolaView Answer on Stackoverflow