Guard exception helper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Ormazabal.PanelMonitoring.Helpers
{
static class Expressions
{
public static string GetMemberName<T>(Expression<Func<T>> expression)
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Expression must be a field or property accessor", "expression");
return memberExpression.Member.Name;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Ormazabal.PanelMonitoring.Helpers
{
public static class Guard
{
public static void NotNull<T>(Expression<Func<T>> parameter)
{
if (parameter.Compile()() != null)
return;
string parameterName = Expressions.GetMemberName(parameter);
throw new ArgumentNullException(parameterName);
}
public static void NotValid<T>(Expression<Func<T>> parameter, Func<T, bool> constraint)
{
Guard.NotNull(parameter);
string parameterName = Expressions.GetMemberName(parameter);
if (constraint(parameter.Compile()()))
return;
throw new ArgumentException("The supplied parameter does not satisfy conditions", parameterName);
}
public static void NotNullOrEmpty(Expression<Func<string>> parameter)
{
Guard.NotNull(parameter);
if (parameter.Compile()() != String.Empty)
return;
string parameterName = Expressions.GetMemberName(parameter);
throw new ArgumentException("The string cannot be empty", parameterName);
}
}
}
public Usage1(object someObject)
{
Guard.NotNull(() => someObject);
}
public UsageWithStrings(string someString)
{
Guard.NotNullOrEmpty(() => someString);
}
public UsageForValidation(int someInt)
{
Guard.NotValid(() => someInt, p => p > 0 && p <= 10);
}