Skip to content

Instantly share code, notes, and snippets.

@troubear
Last active January 22, 2020 09:52
Show Gist options
  • Save troubear/dec4bf4ea9f4f6beb6cc690a6eb83d7a to your computer and use it in GitHub Desktop.
Save troubear/dec4bf4ea9f4f6beb6cc690a6eb83d7a to your computer and use it in GitHub Desktop.
Example of low overhead assertion method
#if UNITY_5_3_OR_NEWER
#define UNITY
#else
#define NON_UNITY
#endif
// Determine whether to strip assertions.
#if !(UNITY && UNITY_ASSERTIONS) && !(NON_UNITY && DEBUG)
#define STRIP_ASSERTION_METHODS
#endif
using System;
using System.Diagnostics;
using JetBrains.Annotations;
public static class MyAssert
{
#if STRIP_ASSERTION_METHODS
[Conditional("NEVER_DEFINED")]
#endif
[DebuggerStepThrough]
[AssertionMethod]
[ContractAnnotation("halt <= condition: false")]
public static void IsTrue<T>(bool condition, T context, [NotNull] Func<T, string> onFailed)
{
#if !STRIP_ASSERTION_METHODS
if (!condition)
{
throw new Exception(onFailed(context) ?? "");
}
#endif
}
}
namespace ConsoleApp1
{
internal class Program
{
private static void Main(string[] args)
{
// Pass
Test(0, 1);
// Fail
Test(1, 0);
}
private static void Test(int a, int b)
{
// No GC occurs after the first time.
MyAssert.IsTrue(a < b, (a, b), args => $"a = {args.a}, b = {args.b}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment