Based on this answer, you could rewrite your method like this:
public static void RequireNotEmpty(Expression<Func<string>> lambda)
{
// Get the passed strings value:
string value = lambda.Compile().Invoke();
// Run the check(s) on the value here:
if (value.Length == 0)
{
// Get the name of the passed string:
string parameterName = ((MemberExpression) lambda.Body).Member.Name;
Console.WriteLine($"ERROR: Non empty value is required for the expression '{parameterName}'.");
}
}
which can then be called like this:
string emptyString = "";
RequireNotEmpty(() => emptyString);
and writes
ERROR: Non empty value is required for the expression 'emptyString'.
Note that above code assumes that you only want to check for strings. If that's not the case, you could use the signature public static void RequireNotEmpty<T>(Expression<Func<T>> lambda)
which will then work for any type T
.
Also I renamed the method to something I find both more readable and more meaningful.
EDIT: Recommendation
After reading your comments, I figured this might be what you want:
public static class Checker
{
private static T GetValue<T>(Expression<Func<T>> lambda)
{
return lambda.Compile().Invoke();
}
private static string GetParameterName<T>(Expression<Func<T>> lambda)
{
return ((MemberExpression) lambda.Body).Member.Name;
}
private static void OnViolation(string message)
{
// Throw an exception, write to a log or the console etc...
Console.WriteLine(message);
}
// Here come the "check"'s and "require"'s as specified in the guideline documents, e.g.
public static void RequireNotEmpty(Expression<Func<string>> lambda)
{
if(GetValue(lambda).Length == 0)
{
OnViolation($"Non empty value is required for '{GetParameterName(lambda)}'.");
}
}
public static void RequireNotNull<T>(Expression<Func<T>> lambda) where T : class
{
if(GetValue(lambda) == null)
{
OnViolation($"Non null value is required for '{GetParameterName(lambda)}'.");
}
}
...
}
And now you can utilise the Checker
class like this:
public string DoStuff(Foo fooObj, string bar)
{
Checker.RequireNotNull(() => fooObj);
Checker.RequireNotEmpty(() => bar);
// Now that you checked the preconditions, continue with the actual logic.
...
}
Now, when you call DoStuff
with an invalid parameter, e.g.
DoStuff(new Foo(), "");
the message
Non empty value is required for 'bar'.
is written to the console.