2

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.

Ronald McDonald
  • 2,843
  • 11
  • 49
  • 67

5 Answers5

10

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.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
3

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;
Roy Goode
  • 2,940
  • 20
  • 22
  • thanks....for my case though, I used var name = Name != null ? Convert.ToString(Name.LastName) : ""; – Ronald McDonald Feb 08 '12 at 22:38
  • This answer is wrong. See [this question](http://stackoverflow.com/questions/10355736/why-does-convert-tostringnull-return-a-different-value-if-you-cast-null) for the reason: because even when Name is not null, if Lastname is null, the result will be null. – shipr Aug 22 '15 at 04:56
  • @shipr That's irrelevant to the question being asked above. My answer addressed the original question - what was causing the runtime NullReferenceException. – Roy Goode Sep 01 '15 at 14:37
2

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.

Oleksi
  • 12,947
  • 4
  • 56
  • 80
2

When Name is null, you can't access a .LastName of a null.

var name = Convert.ToString((Name != null) ? Name.LastName : "");
Leon
  • 3,311
  • 23
  • 20
1

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.

Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52