Tr1et Tr1et - 1 month ago 5
C# Question

C# - Why doesn't Object class have true operator?

Sorry if my question seem stupid.

In C++, this code work:

Foo* foo = new Foo();
if (foo)
....;
else
....;


In C#, this doesn't work:

Object obj = new Object();
if (obj)
....;
else
....;


because
Object
class cannot be implicitly convert to
bool
(obvious, no problem about that), and it doesn't implement
true
operator.

So my question is why doesn't
Object
implement the
true
operator (just check whether itself is null or not, sound easy enough)? Is it just because of code readability or something?

Answer

It's because of code clarity. A lot of design choices for C# were made with the goal that the code should be written in such a way that it is immediately obvious what it is trying to do. If you have something like:

Object obj = ...;
if (obj)
     ....

What does if(obj) mean? Is it checking if obj true? Is it checking if it is null? Is it checking if it is 0? It's not clear to someone glancing at the code and necessitates the programmer to consult the C# documentation to see what this particular syntax is doing. So instead, C# has you say

Object obj = ...;
if (obj == null)
    ....

This way, it is obvious what you are trying to do.

This is the same reason why C# requires you to instantiate your variables as well as declare them before you can use them in code. The value of an uninstantiated variable is ambiguous and depends on the compiler's configuration, so instead of forcing you to do research or perform guesswork, c# instead makes it so you have to code in such a way that your intention is clear.