CommunityToolkit / CommunityToolkit/dotnet
conditionally compiledGuard API
- Dominant language
- C#
- Stars
- 3.8k
- Forks
- 400
- PR merge metrics
- No merged PRs in 30d
Description
### Overview
I've been writing some code along a very hot path and I'm finding some tension between wanting the safety of using Guard clauses but also worrying about the runtime overhead.
Has there been any consideration of defining a sister API that used `ConditionalAttribute` to elide these guards/assertions in release builds?
This can be done external to this library via `#if DEBUG` but there is some precedent with the `Debug.Assert` family of methods.
### API breakdown
```csharp
public static class DebugGuard //Open to any other name...
{
[ConditionalAttribute("Debug")]
public static void IsGreaterThan(T value, T minimum, [CallerArgumentExpression(nameof(value))] string name = "");
[ConditionalAttribute("Debug")]
public static void IsGreaterThanOrEqualTo(T value, T minimum, [CallerArgumentExpression(nameof(value))] string name = "");
...
}
```
### Usage example
```csharp
public void MyHotPath(int index)
{
DebugGuard.IsGreaterThanOfEqualTo(index, 0);
DebugGuard.IsLessThanOf(index, SomeLimit);
}
```
### Breaking change?
No
### Alternatives
```csharp
public void MyHotPath(int index)
{
#if DEBUG
Guard.IsGreaterThanOfEqualTo(index, 0);
Guard.IsGreaterThanOfEqualTo(index, 0);
#endif
}
```
### Additional context
_No response_
### Help us help you
Yes, but only if others can assist
Contributor guide
Assessment
This issue has not been assessed yet.