When working with lists (and similar types like collections and arrays) you might have to check if they have any item in it.
This is can be done as following:
var myList = new List<int>();
if (myList.Count > 0)
{
// ...
}
I got inspired by the python language where by default a list/array object is logical false when it is empty and true when it has items:
myList = []
if myList:
pass
In my opinion, the python code looks much cleaner and I would like to see this in C# as well.
Add a implicit operator to bool for all lists, collections and array types which is false when it is empty and true when it is not.
Here a sample implementation for a new generic custom list:
public class NewList<T> : List<T>
{
public static implicit operator bool(NewList<T> list) => list.Count != 0;
}
Such an implementation would be done in the main classes for List<T>, T[] (arrays) and other collection types.
C# code would look like this:
var myList = new List<int>();
if (myList)
{
// ...
}
Tagging subscribers to this area: @eiriktsarpalis, @jeffhandley
See info in area-owners.md if you want to be subscribed.
.... the traditional thing is usually to do:
using System.Linq;
// ....
if (someEnumerable.Any())
{
// ...
}
... or even just iterate over it; The question is going to be "why check for any?", and in many cases you can just perform whatever.
In C, if (obj) will mean a null check, not an empty check.
Using anything except boolean in if will make things less clear.
This is not the .NET way. It's a reasonable proposal but in the .NET space, the prevailing opinion is that "magic" operations like that are hurting code clarity. Being clever often is not a good idea.
I second what the others have already said in this thread. I doubt we would ever consider such a change, so I'm going to close the issue. Regardless of that, thank you @ice1e0 for taking the time to contribute this proposal.
Most helpful comment
In C,
if (obj)will mean a null check, not an empty check.Using anything except boolean in
ifwill make things less clear.