Allow an object to be treated as an expression #6939
Replies: 3 comments 8 replies
-
Yes. We think it's inherently easy to make mistakes with that sort of truthy-ness testing. So we made a conscious decision that the user or api author always needs to be explicit when dealing with non-booleans. |
Beta Was this translation helpful? Give feedback.
-
This is easy enough to write though: public static bool exists(object? o)
{
return o != null;
} |
Beta Was this translation helpful? Give feedback.
-
You can define public class MyClass {
public static bool operator true(MyClass? obj) => obj != null;
public static bool operator false(MyClass? obj) => obj == null;
} Then you can use it like this: MyClass obj = ...;
if (obj) {
// ...
} Theoretically, with roles and extension everything, you could theoretically add such an operator to I'm with @CyrusNajmabadi , though, that "truthiness" as implemented this way is a vector for unexpected bugs in those languages that allows it. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a reason why we can't write:
Where the language (when
something
is a reference type) implicitly interprets this expression asBeta Was this translation helpful? Give feedback.
All reactions