diff --git a/content/articles/dotnet/boxing-bools.md b/content/articles/dotnet/boxing-bools.md new file mode 100644 index 0000000..db9e227 --- /dev/null +++ b/content/articles/dotnet/boxing-bools.md @@ -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). diff --git a/content/articles/dotnet/boxing-nullable-value-types.md b/content/articles/dotnet/boxing-nullable-value-types.md index 3cc9b82..2b96644 100644 --- a/content/articles/dotnet/boxing-nullable-value-types.md +++ b/content/articles/dotnet/boxing-nullable-value-types.md @@ -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: