开发者

Console.WriteLine correctly handle null string

开发者 https://www.devze.com 2023-01-24 06:58 出处:网络
Just find that Console.WriteLine can handle null string correctly like Console.WriteLine((string)null);

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

Can I assume that most class library handle null refere开发者_运维技巧nce correctly?


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.


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.


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


In general, when the argument (doesn't matter if string or any other type) is required to do something the method will usually crash with exception when that argument 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 hand, when the argument is not required the method will usually "swallow the frog" when it's null and treat it as some default value, for example empty string. In the case of WriteLine method of the Console object, it doesn't really need the string, it simply write it to the console so it doesn't care if it's null.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号