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

Solution 1:

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:

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:

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:

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 5:

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