tags:

views:

470

answers:

8

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
}
A: 

If obj is a type that you created, you can define a user defined implicit conversion to bool.

Peter Tate
I wouldn't recommend this as 'best practice' though...
dtb
I wouldn't either! This is the only way I know of to get the syntax Alex is asking for.
Peter Tate
+13  A: 

Short answer:

In C#:

  • true : Always true
  • false : Always false

Everything else is not a boolean value.

dtb
Not true. See my answer below.
Trumpi
My answer doesn't contradict yours. Types can implement implicit conversions to bool or your 'true' operator, but any value of such a type is still not of type 'bool' :)
dtb
I read your answer again: it actually contradicts the spec.
Trumpi
Hold on - I take that back. There is a difference between a boolean and a boolean expression.
Trumpi
+23  A: 

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.

Dan Herbert
Ok i guess that answers my question :)
Alex
Implicit conversions have nothing to do with dynamic typing.
Pete Montgomery
Dan Herbert
So all you dinosaurs can stop writing if(0 == i)...
Benjol
+2  A: 

The if statement evaluates something that can be converted to / equates to / returns boolean, or a boolean itself... checking for null like obj != null is one such expression,

'if (obj)' can work if only if obj is able to convert to bool, not if it is null.

CRice
+1  A: 

C# is a statically-typed language, that is to say that the type of objects matter in setting what it is.

For example, "4" != 4.

JavaScript, however is a dynamically-typed language, so the types have little importance.

So in JavaScript, "4" == 4.

The "truthy" values are values that just happen to satisfy x == true, while the "falsey" values do not.

Without type safety, certain features such as overloading will yield unpredictable behaviors.

For more info, you can see here.

MiffTheFox
No, static Vs dynamic typing has nothing to do with this.
Pete Montgomery
+8  A: 

Code like that will (and should) fail to compile. If you specifically want to override that behavior, you can create an implicit conversion to boolean. Something like this:

public class Foo {
    public static implicit operator bool(Foo me) {
        if (me == null) {
            return false;
        }

        return true; // maybe add more logic before saying True
    }
}

I would call that a bad practice because, to a coder not familiar with your project, it's not immediately clear what logic feeds the boolean conversion. The more idiomatic way to do this would be to explicitly tell the reader what your code is doing, like the built in String class does, with a static helper function:

if (String.IsNullOrEmpty(str){
    // ...
}

Code is only written once, and read often; optimize for readability.

ojrac
+11  A: 

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.

Eric Lippert
+7  A: 

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.

Trumpi
This is the correct answer. All of the answers that fail to mention operator true/operator false overloads are somewhat incomplete. It's also correct that what the OP is trying to do isn't really a good idea, but this is the best way to do it.
Doug McClean