Skip to content

Instantly share code, notes, and snippets.

@adammyhre
Last active April 25, 2025 10:26
Show Gist options
  • Save adammyhre/82d495ab99e2c59a19362119b2d43194 to your computer and use it in GitHub Desktop.
Save adammyhre/82d495ab99e2c59a19362119b2d43194 to your computer and use it in GitHub Desktop.
Unity Preconditions Class
using System;
public class Preconditions {
Preconditions() { }
public static T CheckNotNull<T>(T reference) {
return CheckNotNull(reference, null);
}
public static T CheckNotNull<T>(T reference, string message) {
// Can find OrNull Extension Method (and others) here: https://github.com/adammyhre/Unity-Utils
if (reference is UnityEngine.Object obj && obj.OrNull() == null) {
throw new ArgumentNullException(message);
}
if (reference is null) {
throw new ArgumentNullException(message);
}
return reference;
}
public static void CheckState(bool expression) {
CheckState(expression, null);
}
public static void CheckState(bool expression, string messageTemplate, params object[] messageArgs) {
CheckState(expression, string.Format(messageTemplate, messageArgs));
}
public static void CheckState(bool expression, string message) {
if (expression) {
return;
}
throw message == null ? new InvalidOperationException() : new InvalidOperationException(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment