In JavaScript there is the idea of truthy and falsy values.
e.g.
Is there an equivalent list of truthy and falsey values in the C# language on the .NET framework?
The reason I would like to know this is that I find myself doing the following
if(obj != null) { // Do something with the object }
When I could write the following
if(obj) { // Do something with the object }
C# only has literal true
and false
values.
C# requires you to be very explicit in your declarations since it is a strongly-typed language, as opposed to JavaScript which can do implicit conversions when needed.
It is important to note that "strong typing" is not the reason why C# doesn't implicitly convert to "truthy/falsy" values. The language intentionally is trying to avoid the pitfalls of other compiled languages like C++ where certain values can be truthy, like '0
' or '1
' which could allow you to make a syntactical mistake you might not notice until runtime when your code behaves unexpectedly.
By default, C# only provides true
and false
.
However, you can have your own custom types becomes "truthy" and "falsey" by implementing the true
operator. When a type implements the true
operator, instances of that type can be used as a boolean expression. From section 7.19 of the C# Language Specification:
When a boolean expression is of a type that cannot be implicitly converted to bool but does implement operator true, then following evaluation of the expression, the operator true implementation provided by that type is invoked to produce a bool value.
The
DBBool
struct type in §11.4.2 provides an example of a type that implements operator true and operator false.
Here is a code snippet of a declaration of the true
operator (which will probably accomplish what you wanted to do in your question):
public static bool operator true(MyType myInstance) { return myInstance != null; }
If you implement the true
operator, then you must implement the false
operator too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With