Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

operators

c#

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?

like image 450
Tr1et Avatar asked Jan 17 '26 15:01

Tr1et


1 Answers

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.

like image 103
Abion47 Avatar answered Jan 20 '26 05:01

Abion47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!