Is it possible to check the value of a parameter natively using an attribute? I have seen some system attributes like [FromUri] used this way. I'm hoping for something like this:
public void Method([NotNull] string name, [NotNull] DateTime? date)
{ }
where NotNull is an attribute that checks the value to see if it is null. If the value is null it will throw an error.
Here is what I currently have
I'm currently using a static helper class that takes an expression and the parameter itself to determine whether the value is null and uses the expression to determine the name of the parameter.
// Invoke method within ArgumentHelper class
ArgumentHelper.RequireNotNullOrEmpty(() => state, state);
// Method within static class ArgumentHelper
public static void RequireNotNullOrEmpty<T>(this Expression<Func<T>> argumentExpression, string value)
{
var body = ((MemberExpression)argumentExpression.Body);
if (string.IsNullOrEmpty(value))
{
// Throw error "Required field '" + body.Member.Name + "' is missing.";
}
}
Bonus: It would also be nice if I could somehow get the name of the variable without passing a string with its name, just like my current solution.
== null[FromUri]property only works the way it does because the caller (which is the web api itself) checks the attributes of the method it's trying to call and if it sees that attribute, it knows to insert the value from the uri. The attribute itself doesn't do that. It's the callers responsibility.[Required]tag that makes sure the property is not null and if it is it throws an error. Isn't this similar to what I'm looking for, or am I misunderstanding what it is actually doing? BTW I'm not trying to be conflicting, I'm just truly trying to understand this stuff. I'm still learning. :)[Required]tag doesn't do anything at all unless the code using those properties actually checks it. It used for validation where the validation code will run through all the properties in your model and check to see if they have the[Required]attribute and if they do, it checks for null. It's still the responsibility of the calling code to actually check. By itself, it does nothing.