CommunityToolkit / CommunityToolkit/dotnet
Guard-like helper methods for warnings
- Dominant language
- C#
- Stars
- 3.8k
- Forks
- 400
- PR merge metrics
- No merged PRs in 30d
Description
### Overview
The `Guard` static class is great! But it only makes sense when we are willing to throw and handle exceptions.
Sometimes, for debugging purposes, we would like to safely assert some assumptions and report them in the output.
Therefore, I would like to suggest a new class similar to `Guard`, maybe named `Test` or `Trace` or `LogIf`, that does pretty much the same thing than `Guard` except that it does *not* throw exceptions, but instead display a message through `Debug.WriteLine` and would act only with the DEBUG build constant.
### API breakdown
```csharp
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace CommunityToolkit.Diagnostics;
///
/// Helper methods to verify conditions when running code.
///
[DebuggerStepThrough]
public static partial class Trace
{
///
/// Asserts that the input value is not .
///
/// The type of reference value type being tested.
/// The input value to test.
/// The message to display when value is not null.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Conditional("DEBUG")]
public static void IsNotNull(T? value, string message)
{
if (value is null)
{
Warn(message);
}
}
[...]
[Conditional("DEBUG")] // => https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=net-7.0
private void Warn(string message)
{
Debug.WriteLine(message);
Debug.Assert(false, message);
}
}
```
### Usage example
```csharp
void Foo(object param)
{
Trace.IsNotNull(param, "param is null, it means X is happening");
}
```
### Breaking change?
No
### Alternatives
```csharp
void Foo(object param)
{
LogIf.IsNull(param, "param is null, it means X is happening");
}
```
### Additional context
_No response_
### Help us help you
No, just wanted to propose this
Contributor guide
Assessment
This issue has not been assessed yet.