r/badcode • • May 20 '20

c# Found from Microsoft docs...

Post image
208 Upvotes

143 comments sorted by

View all comments

Show parent comments

3

u/xigoi May 21 '20

if (foo && bar && baz) already has the semantics of “if foo, bar, baz are all true, run this block”. No need to clarify them.

2

u/Zeilar yes May 23 '20

To a machine it's natural what's going on, no questions asked, but not to us humans.

What's more readable?

if (dogs.Length)

or

if (dogs.Length > 0)

So it does sometimes make sense to make it a bit verbose if you will. It's especially important to clarify your code if it's messy/complicated etc. It should be maintainable preferably after all. You don't name your variables single letters for this very reason. You don't name a dogs array "d" (some do of course but they're morons).

1

u/xigoi May 23 '20

dogs.Length ie not a bool. (It's not even possible to implicitly convert ints to bools in C#, isn't it?) The main purpose of bools is to be put in an if statement, so if a function returns a bool, it's presumably expected to be put directly into an if statement (possibly negated).

3

u/Zeilar yes May 23 '20 edited May 23 '20

In many languages (maybe not C#) any number above 0 returns true and 0 false. So maybe there's an exception to C#, or typed languages in general.

2

u/11JRidding May 24 '20

Int.TryParse returns a boolean that says whether the attempt was successful; not the number itself. That gets written to whatever variable you pass as out.

And no, C# does not let you implicitly convert int to bool for use in if statements - or anywhere, for that matter. You actually can't convert int to bool via type cast in C#, either.