/// <summary> /// Checks if the provided condition is true or false. /// If true it will throw an <see cref="ArgumentException"/>. /// </summary> /// <param name="ifChainer">The semantic if object.</param> /// <param name="obj">Reference object to be checked for null.</param> /// <param name="message">Message to be provided to the <see cref="ArgumentException"/>.</param> /// <exception cref="ArgumentException">Throws <see cref="ArgumentException"/> if <paramref name="obj"/> is null.</exception> public static IIfSemanticChainer <ArgumentException> Now(this IIfSemanticChainer <ArgumentException> ifChainer, string message) { #if DEBUG //We need to check this because someone may mess up and not call ?.Now(). Big preformance impact if they don't if (ifChainer != null) { //Just throw with the provided arguments throw new ArgumentException(message); } else { throw new InvalidOperationException($"You should not call Now when the chain is null. Use null-conditional operator like this: ?.Now(...)"); } #else //We need to check this because someone may mess up and not call ?.Now(). Big preformance impact if they don't if (ifChainer != null) { //Just throw with the provided arguments throw new ArgumentException(message); } else { return(ifChainer); } #endif }
//We need this static ctor to populate If as soon as the type is accessed //in a thread safe way. /// <summary> /// Initializes static members of the <see cref="Throw{TExceptionType}"/> type. /// </summary> static Throw() { //After all that we need to populate the IfSemanticChainer //This is the only real reason anyone is accessing this class //Read some comments below on why this is an instance and not a static If = new IfSemanticChainer <TExceptionType>(new CompiledLambdaGenericExceptionFactory <TExceptionType>()); }
//These methods are generic, sadly, because we can't use System.Object as the parameter type. //.Net will implictly box the values and we'll be checking non-reference types. //Don't worry about preformance though, .Net will only compile the methods once. /// <summary> /// Checks if the provided <paramref name="obj"/> is null. /// If null it will throw an <see cref="ArgumentNullException"/>. /// </summary> /// <typeparam name="TRefType">The type of reference.</typeparam> /// <param name="ifChainer">The semantic if object.</param> /// <param name="obj">Reference object to be checked for null.</param> /// <exception cref="ArgumentNullException">Throws <see cref="ArgumentNullException"/> if <paramref name="obj"/> is null.</exception> public static IIfSemanticChainer <ArgumentNullException> IsNull <TRefType>(this IIfSemanticChainer <ArgumentNullException> ifChainer, TRefType obj) where TRefType : class { //The idea here is we'll chain using ?. to an extension method for Now() if (obj == null) { return(ifChainer); } else { return(null); } }