-
Notifications
You must be signed in to change notification settings - Fork 474
/
NotNullExtensions.cs
71 lines (64 loc) · 1.87 KB
/
NotNullExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
namespace SharpCompress;
public static class NotNullExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IEnumerable<T> Empty<T>(this IEnumerable<T>? source) =>
source ?? Enumerable.Empty<T>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IEnumerable<T> Empty<T>(this T? source)
{
if (source is null)
{
return Enumerable.Empty<T>();
}
return source.AsEnumerable();
}
#if NETFRAMEWORK || NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T NotNull<T>(this T? obj, string? message = null)
where T : class
{
if (obj is null)
{
throw new ArgumentNullException(message ?? "Value is null");
}
return obj;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T NotNull<T>(this T? obj, string? message = null)
where T : struct
{
if (obj is null)
{
throw new ArgumentNullException(message ?? "Value is null");
}
return obj.Value;
}
#else
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T NotNull<T>(
[NotNull] this T? obj,
[CallerArgumentExpression(nameof(obj))] string? paramName = null
)
where T : class
{
ArgumentNullException.ThrowIfNull(obj, paramName);
return obj;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T NotNull<T>(
[NotNull] this T? obj,
[CallerArgumentExpression(nameof(obj))] string? paramName = null
)
where T : struct
{
ArgumentNullException.ThrowIfNull(obj, paramName);
return obj.Value;
}
#endif
}