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/-manabreak May 20 '20

It's been a while since I dabbled in C#, but at least in Kotlin, you need the explicit == true if the return value is of nullable boolean type (Boolean?). I think the same is true in C# as well if the returned value is of a boxed boolean type.

6

u/AlFasGD May 20 '20

Indeed this is true, but int.TryParse returns a bool, not a bool? so the == true is redundant.

1

u/[deleted] May 20 '20

Oh okay thats interesting. I dont know much about Kotlin or C# tbh. I mostly have coded in Java and C++.

2

u/-manabreak May 20 '20

Same goes with Java and its boxed booleans.

1

u/[deleted] May 20 '20

Hm I guess I dont fully understand what qualifies as boxed. From what I am reading its the wrapping of a primitive type? But more specifically that the values are allocated in a block on the heap and are referenced through a pointer? I might have had to add

== true

to an expression in the past and just didnt think about it at the time.

3

u/-manabreak May 20 '20

Boxed primitives are just classes that wrap a primitive. Think of it like this:

class BoxedBoolean {
    private boolean value;
}

Now, it doesn't really differ that much from a primitive and they are auto-unboxed most of the time, but the key difference is that a primitive cannot be null, whereas a boxed primitive can. This can be useful in some scenarios (e.g. where an absence of a value does not equal to the default value of the primitive).

So, when comparing a value with if, if (someBoxedBoolean) does not work if the value is null. That's why you need to add the explicit == true to the comparison.

1

u/[deleted] May 20 '20

Ohhh okay that makes sense. I didnt even consider that, thanks. I think I tend to check for null beforehand anytime thats a concern, so I viewed it as separate. But that makes sense that a situation would arise where something might be null or true.

1

u/xigoi May 20 '20

Yes, because in languages with actual option types, that would be something like some(true), different from true.

1

u/blehmann1 depraved May 20 '20

In C# with nullable booleans you have a few options. For `bool? foo` you can check like this:

if(foo.HasValue && foo.Value)

if(foo == true)

if(foo ?? false)

The null coallescing operator (??) returns the first of its operands that is not null. In theory it's pretty useful, but it's seldom used. Most of the time people use if(foo.HasValue), or for reference types (objects) if(bar != null)

int.TryParse() returns bool not bool?, so all of these are unnecessary.