0

I have a function which return type is Object, when function return NULL, I am getting a object reference not set error. If I Use .ToString(). So how do I override the .ToString() to return empty when it returns null??

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
  • The thing to do here is to test for null before attempting to call ToString() – Alex K. Sep 02 '16 at 11:44
  • Overriding will not help, as Null is not an object type to call the overridden method – Mrinal Kamboj Sep 02 '16 at 11:46
  • You could `override` your `.ToString()` , use `.IsNullOrEmtpy()`to check or use _null propagation_ Just google any of these and let us know if u need further help. – uTeisT Sep 02 '16 at 11:47

2 Answers2

2

That's impossible, you can't call a method on a null-object, aka you can't call a method on something that isn't there.

The only thing you can do is check for null:

if(theObj == null)
    Console.WriteLine("empty");

Or alternatively:

var someName = theObj != null ? theObj.ToString() : "empty";
Kenneth
  • 28,294
  • 6
  • 61
  • 84
1

Before convert that object to string using ToString(), please check the object is null.

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44