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
}
C# only has literal
trueandfalsevalues.C# requires you to be very explicit in your declarations. This behaves like other popular strongly-typed languages, as opposed to JavaScript which can do implicit conversions when needed.
It should be noted for clarity 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 some 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.