Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.WriteLine correctly handle null string

Just find that Console.WriteLine can handle null string correctly like Console.WriteLine((string)null);

Can I assume that most class library handle null reference correctly?

like image 984
user496949 Avatar asked Nov 11 '10 08:11

user496949


2 Answers

No.

This fully depends on the method you call. See the MSDN documentation per method on what to expect when you pass a null.

It's never safe to make assumptions about null when calling into someone else's API or library, especially if you don't have its source code to use as a reference. Always read the docs. And if the docs don't say, code defensively.

However, the library methods are programmed in such a manner that when they do not accept a null, they will throw an exception telling you that it's not a valid argument.

like image 140
Pieter van Ginkel Avatar answered Sep 28 '22 07:09

Pieter van Ginkel


Well... Yes.

You can expect that (almost) all classes will handle null references correctly.

However, I feel that what you mean by "correctly" is not the same as what the author of the class means.

For instance, if you try to open a file and pass null for the path to the file to open, it will not fail silently, it will throw an exception.

If that is what you mean by "handle correctly", then sure. In fact, I hope all classes handles null references correctly.

But don't expect the program to just trundle on as if nothing happened.

like image 42
Lasse V. Karlsen Avatar answered Sep 28 '22 07:09

Lasse V. Karlsen