We developers don’t like documentation. We don’t like to read it, and we even more we don’t like to write it. But sometimes it is worth to read it. Like when you find out that by using datetime in SQL DB you got a milliseconds precision but only if it ends on 0,3,7 (link). That was brought to my attention by Lech Osiński at Programistok 2017. Lech was describing some WTF experience when dealing with datetime if you don’t read the docs. I had a similar experience this time with .NET.
I was asked why this
returns true. My first impression was WTF, it should not return true. Empty string doesn’t have all characters equal to ‘+’. But a quick check in LINQPad confirmed that it does. So what now? Well we could go to read the docs but who would do that? What we did (as this now become a office problem :]) decompiled the All method and check how it is implemented. So All returns false when it predicate returns false but if for any of the chars it will not be false it will return true. So for an empty string, the predicate will never be executed thus All will return true.
A bit counter-intuitive I would say. Counter-intuitive? Yes – but of course documented. If you got to the docs for All it’s clear that for an empty collection (in this case, an empty string) it will return true.
true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
So read the documentation and don’t be surprised when something is not working as expected – at least it’s documented.
Photo by: https://unsplash.com/photos/wk833OrQLJE
Founder of Octal Solutions a .NET software house.
Passionate dev, blogger, occasionally speaker, one of the leaders of Wroc.NET user group. Microsoft MVP. Podcaster – Ostrapila.pl