[ACCEPTED]-Console.WriteLine correctly handle null string-console-application

Accepted answer
Score: 10

No.

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

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

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

Score: 5

Well... Yes.

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

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

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

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

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

Score: 0

That depends entirely on what you mean by 4 "correctly" and on the method itself. Unless 3 you mean "could throw an exception because 2 it was expecting an actual string", then 1 no.

Score: 0

In general, when the argument (doesn't matter 14 if string or any other type) is required 13 to do something the method will usually 12 crash with exception when that argument 11 is null.

Couple of examples:

  1. Files.. can't open "null" file, so --> error.
  2. Parse --> can't parse "null", so --> error. (Yeah, they added TryParse in 2.0)

On the other 10 hand, when the argument is not required 9 the method will usually "swallow the frog" when 8 it's null and treat it as some default value, for 7 example empty string. In the case of WriteLine 6 method of the Console object, it doesn't 5 really need the string, it simply write it to 4 the console so it doesn't care if it's null.

So 3 like others here said, it depends on what 2 method you try to use and you better read 1 before trying to pass null values.

More Related questions