Reputation: 895
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?
Upvotes: 2
Views: 365
Reputation: 24726
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 local 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.
Upvotes: 6
Reputation: 660297
The fundamental answer to your question is the one given in the accepted answer: because C# was designed to avoid, not perpetuate the design errors of C.
But more specifically: you ask why a type does not implement operator true
. The answer to that question is: the purpose of operator true
is to implement the short circuiting &&
and ||
operators. Since there is no desire to have object
implement either &
or &&
or |
or ||
, there is no reason to implement operator true
or operator false
.
Upvotes: 5
Reputation: 283733
Boxing.
It would really be horribly confusing for conditionals involving booleans to do the exact opposite when the value is boxed.
What do you want from:
object o = false; // Yes, this is legal, it makes a boxed System.Boolean
if (o) { ... }
For this reason it's fine for bool-like types to be tested in conditions, but not for System.Object
which is the base class for all boxed values.
Upvotes: 1