Skip to content

Commit

Permalink
Add article about nullable value types
Browse files Browse the repository at this point in the history
  • Loading branch information
skrysmanski committed Mar 19, 2024
1 parent 6cbe7b3 commit c83e0cf
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions content/articles/dotnet/boxing-nullable-value-types.md
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;
}
```

0 comments on commit c83e0cf

Please sign in to comment.