Skip to content

Commit df7a1ec

Browse files
john-h-kSergio0694
authored andcommitted
Add NullableHelper
1 parent 6ec8c8c commit df7a1ec

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System;
2+
using System.Runtime.CompilerServices;
3+
4+
5+
namespace Microsoft.Toolkit.HighPerformance.Helpers
6+
{
7+
/// <summary>
8+
/// Helpers to perform operations on nullable value types
9+
/// </summary>
10+
public static class NullableHelper
11+
{
12+
/// <summary>
13+
/// We use this type to publically expose the fields of a Nullable{T} type
14+
/// </summary>
15+
private struct NullableHelperMap<T>
16+
where T : struct
17+
{
18+
public byte HasValue;
19+
public T Value;
20+
}
21+
22+
/// <summary>
23+
/// Returns a ref <typeparamref name="T"/> to the value of <paramref name="nullable"/> if <see cref="Nullable{T}.HasValue"/> is true,
24+
/// else, default(T)
25+
/// </summary>
26+
/// <typeparam name="T">The type of the underlying value</typeparam>
27+
/// <param name="nullable">The <see cref="Nullable{T}"/></param>
28+
/// <returns>A ref <typeparamref name="T"/> to the underlying value or default(T)</returns>
29+
public static ref T GetValueOrDefaultRef<T>(this ref T? nullable)
30+
where T : struct
31+
{
32+
return ref Unsafe.As<T?, NullableHelperMap<T>>(ref nullable).Value;
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)