Skip to content

Commit f9f1bd1

Browse files
add NotNullWhen attributes to TryGet
1 parent c3176de commit f9f1bd1

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// this gives us the NotNullWhen attribute
2+
// if you remove this, the code wont compile
3+
4+
// ReSharper disable once CheckNamespace
5+
namespace System.Diagnostics.CodeAnalysis;
6+
7+
[AttributeUsage(AttributeTargets.Parameter)]
8+
public sealed class NotNullWhenAttribute(bool returnValue) : Attribute
9+
{
10+
public bool ReturnValue { get; } = returnValue;
11+
}

Helpers/ResultSystem/TryGet.cs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System.Diagnostics.Contracts;
1+
using System.Diagnostics.CodeAnalysis;
2+
using System.Diagnostics.Contracts;
23
using SER.Helpers.Exceptions;
34

45
namespace SER.Helpers.ResultSystem;
@@ -11,16 +12,16 @@ public sealed class TryGet<TValue>(TValue? value, string? errorMsg)
1112
public Result Result => new(WasSuccess, ErrorMsg ?? "");
1213

1314
[Pure]
14-
public bool HasErrored(out string error)
15+
public bool HasErrored([NotNullWhen(true)] out string? error)
1516
{
16-
error = ErrorMsg ?? "";
17+
error = ErrorMsg;
1718
return !WasSuccess;
1819
}
1920

2021
[Pure]
21-
public bool HasErrored(out string error, out TValue val)
22+
public bool HasErrored([NotNullWhen(true)] out string? error, [NotNullWhen(false)] out TValue? val)
2223
{
23-
error = ErrorMsg ?? "";
24+
error = ErrorMsg;
2425
val = Value!;
2526
return !WasSuccess;
2627
}
@@ -32,7 +33,7 @@ public bool WasSuccessful()
3233
}
3334

3435
[Pure]
35-
public bool WasSuccessful(out TValue val)
36+
public bool WasSuccessful([NotNullWhen(true)] out TValue? val)
3637
{
3738
val = Value!;
3839
return WasSuccess;
@@ -79,18 +80,18 @@ public static TryGet<TValue> Success(TValue value)
7980
[Pure]
8081
public TryGet<TTarget> OnSuccess<TTarget>(Func<TValue, TTarget> transform)
8182
{
82-
if (HasErrored(out var error, out TValue val))
83+
if (HasErrored(out var error, out var val))
8384
{
8485
return error;
8586
}
86-
87+
8788
return transform(val);
8889
}
8990

9091
[Pure]
9192
public TryGet<TTarget> OnSuccess<TTarget>(Func<TValue, TryGet<TTarget>> transform)
9293
{
93-
if (HasErrored(out var error, out TValue val))
94+
if (HasErrored(out var error, out var val))
9495
{
9596
return error;
9697
}

0 commit comments

Comments
 (0)