-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add article about nullable value types
- Loading branch information
1 parent
6cbe7b3
commit c83e0cf
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
--- | ||
title: Boxing Nullable Value Types in C# | ||
topics: | ||
- csharp | ||
- dotnet | ||
--- | ||
|
||
A nullable value type value (e.g. `int?`) loses its nullability type information when it's boxed: | ||
|
||
**Concrete value:** | ||
|
||
```c# | ||
int? valueType = 42; | ||
object? boxed = valueType; | ||
Console.WriteLine(boxed?.GetType()); // System.Int32 | ||
``` | ||
|
||
**Null value:** | ||
|
||
```c# | ||
int? valueType = null; | ||
object? boxed = valueType; | ||
Console.WriteLine(boxed is null); // true | ||
``` | ||
|
||
This also means that using `Nullable.GetUnderlyingType()` is useless for boxed value types: | ||
|
||
```c# {hl_lines="9"} | ||
public void MyMethod(object? value) | ||
{ | ||
if (value is null) | ||
{ | ||
return; | ||
} | ||
|
||
// Always false! | ||
bool isNullable = Nullable.GetUnderlyingType(value.GetType()) != null; | ||
} | ||
``` |