Ronald McDonald
Ronald McDonald

Reputation: 2911

Convert.ToString not handling null

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

Answers (5)

Brian Rasmussen
Brian Rasmussen

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

Roy Goode
Roy Goode

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

Adam Mihalcin
Adam Mihalcin

Reputation: 14458

As written, your code says to do the following:

  1. Find the object Name in memory.
  2. Find the LastName field on the object Name
  3. Pass that Name.LastName field to the Convert.ToString method
  4. Assign the result to name

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

Leon
Leon

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

Oleksi
Oleksi

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

Related Questions