Reputation: 2911
I've read that Convert.ToString should handle null, but it doesn't work when it's passed a null object in my code
In this case the object "Name" is null.
var name = Convert.ToString(Name.LastName);
I get Object reference not set to an instance of an object.
Upvotes: 2
Views: 8488
Reputation: 116401
That has nothing to do with Convert.ToString
. You're trying to access LastName
via a null reference. That's a runtime exception.
Both Name
and LastName
can be null here. Convert.ToString
will never be called in the code above if Name
is null.
Upvotes: 10
Reputation: 2990
The exception is not caused by Convert.ToString()
.
The exception is in your code because you are trying to get the value of LastName
from a null reference. This causes the runtime exception.
To fix it, you'll need to check that Name
is not null before you try to access LastName
.
var name = Name != null ? Convert.ToString(Name.LastName) : null;
Upvotes: 3
Reputation: 14458
As written, your code says to do the following:
Name
in memory.LastName
field on the object Name
Name.LastName
field to the Convert.ToString
methodname
Your code fails on step 2. Since Name
is null, there is no Name.LastName
field available, so you never make it to step 3. Therefore, it doesn't matter whether or not Convert.ToString
correctly handles a null parameter, since the NullReferenceException
was thrown before you even called Convert.ToString
.
Upvotes: 1
Reputation: 3401
When Name
is null, you can't access a .LastName of a null
.
var name = Convert.ToString((Name != null) ? Name.LastName : "");
Upvotes: 2
Reputation: 13097
In this case, when C# evaluates Name.LastName it will crash. This is because you are really evaluating Null.LastName, which doesn't make sense. Conver.ToString(Null), will work.
Upvotes: 2