Tuesday, September 10, 2024

Different meanings of "any" in C# and Python

I first learned to program in Python and now work in C#.

Python has the function "any", which takes in any number of parameters and checks whether any of them are truthy. This makes sense since Python has a concept of object truthiness.

C# has the Linq method "Any", which takes in an IEnumerable<T> and a Func<T,bool>. It calls the function on each element of the collection and checks whether any of these calls returns "true". This makes sense since C# has no concept of truthiness; a hypothetical C# "Any" method that did not pass in a function could only take a collection of boolean values.

Additionally, C# has a separate Linq method "Any" that takes in only a collection. It checks whether the collection has any elements in it. C# can have two methods called "Any" since it, unlike Python, has method overloading.

Despite this very logical reasoning, I periodically end a long bug hunt by discovering that, having a list of bools, I called "Any()" on it instead of "Any(a => a)".

I miss F#'s "IsEmpty".

If you can, avoid using the same term for two different concepts.

No comments:

Post a Comment

For beginners: Christmas gift exchange using Google Apps Script

My family does an annual Christmas gift exchange, but we had to keep redealing the names because someone invariably drew his own name. With ...