c# truthy and falsy values

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.


The correct answer to your question is found in section 7.19 of the C# 3.0 specification, which you can easily find on the internet. For your convenience, the relevant text is:

7.19 Boolean expressions

A boolean-expression is an expression that yields a result of type bool.

The controlling conditional expression of an if-statement [...] is a boolean-expression. [...]

A boolean-expression is required to be of a type that can be implicitly converted to bool or of a type that implements operator true. If neither requirement is satisfied, a compile-time error occurs.

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.

There are no types other than bool itself which are implicitly convertible to bool via a built-in conversion, but of course, user-defined implicit conversions to bool can be defined by the user.

Tags:

C#

.Net