Skip to content

Commit

Permalink
Add article about boxing bools in C#
Browse files Browse the repository at this point in the history
  • Loading branch information
skrysmanski committed May 12, 2024
1 parent c0555d9 commit ecc6c6e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
26 changes: 26 additions & 0 deletions content/articles/dotnet/boxing-bools.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: Boxing bool values
topics:
- csharp
- dotnet
- boxing
---

When boxing value types in C#/.NET, an object on the heap is created.

**What happens when you box a `bool` value?**

Since there are only two possible values, are the box objects reference equal?

The answer is: **No. For example, boxing `true` twice results in different objects.**

Consider this code:

```c#
var obj1 = (object)true;
var obj2 = (object)true;

Console.WriteLine(ReferenceEquals(obj1, obj2)); // prints "false"
```

There are not even {{< abbr "BCL" "Base Class Library" >}} constants for `true` and `false` (unlike Java). This issue is behavior is discussed in this [GitHub issue](https://github.com/dotnet/runtime/issues/47596).
1 change: 1 addition & 0 deletions content/articles/dotnet/boxing-nullable-value-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ title: Boxing Nullable Value Types in C#
topics:
- csharp
- dotnet
- boxing
---

A nullable value type value (e.g. `int?`) loses its nullability type information when it's boxed:
Expand Down

0 comments on commit ecc6c6e

Please sign in to comment.