Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# truthy and falsy values

Tags:

c#

.net

In JavaScript there is the idea of truthy and falsy values.

e.g.

  • 0 : Always false
  • 1 : Always true
  • '0' : Always true
  • '1' : Always true

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 } 
like image 565
Alex Avatar asked May 27 '09 01:05

Alex


2 Answers

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.

like image 102
Dan Herbert Avatar answered Sep 19 '22 19:09

Dan Herbert


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.

like image 38
Sir Rippov the Maple Avatar answered Sep 19 '22 19:09

Sir Rippov the Maple