Created
July 7, 2017 06:16
-
-
Save Storm-BE/5664966d964d4d46c02dbfe9ffc4cfa0 to your computer and use it in GitHub Desktop.
ArgumentValidation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using JetBrains.Annotations; | |
namespace Helpers | |
{ | |
public static class ArgumentValidation | |
{ | |
public static void ThrowIfNull<T>([ValidatedNotNull] [NoEnumeration] T argument) | |
where T : class | |
{ | |
ThrowIfNull(nameof(argument), argument); | |
} | |
/// <summary> | |
/// Throws if null. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="name">The name of the argument.</param> | |
/// <param name="argument">The argument value.</param> | |
/// <exception cref="System.ArgumentNullException">The argument is null.</exception> | |
public static void ThrowIfNull<T>(string name, [ValidatedNotNull] [NoEnumeration] T argument) | |
where T : class | |
{ | |
if (argument == null) | |
throw new ArgumentNullException(name); | |
} | |
public static T ValidatedNotNull<T>([ValidatedNotNull] [NoEnumeration] this T argument, string name) | |
where T : class | |
{ | |
ThrowIfNull(name, argument); | |
return argument; | |
} | |
public static string ValidatedNotNullOrEmpty([ValidatedNotNull] [NoEnumeration] this string argument, | |
string name) | |
{ | |
ThrowIfNullOrEmpty(name, argument); | |
return argument; | |
} | |
/// <summary> | |
/// Throws if null or empty. | |
/// </summary> | |
/// <param name="argument">The argument.</param> | |
/// <exception cref="System.ArgumentNullException">The argument is null or is empty.</exception> | |
public static void ThrowIfNullOrEmpty([ValidatedNotNull] string argument) | |
{ | |
ThrowIfNullOrEmpty(nameof(argument), argument); | |
} | |
public static void ThrowIfNullOrEmpty(string name, [ValidatedNotNull] string argument) | |
{ | |
if (string.IsNullOrEmpty(argument)) | |
throw new ArgumentNullException(name); | |
} | |
} | |
// Tells CodeAnalysis that this argument is being validated | |
// to be not null. Great for guard methods. | |
[AttributeUsage(AttributeTargets.Parameter)] | |
internal sealed class ValidatedNotNullAttribute : Attribute | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment