I want to write a simple Validate Method like FluentValidation
I wrote this simple code:
public static class ExtensionMethods<T> where T : class
{
public static bool Validate(Func<T, bool> expression)
{
//What I should write?????
}
}
I don’t know what should I write in method body and how I can use that.
EDIT 1 :
I want to write such this code for all objects:
ExtensionMethods<MyObject>.Validate(o=>o.ID == 1).AddMessage(....
First of all, the key to fluent interfaces is that your methods –
Validate, in this case – don’t return bool, but rather return an object that can be called again. So let’s say it’s T here. Additionally, you’re not really using extension method syntax, you’re just defining a static method. And one last thing before we start – you set the generic parameter T in your class definition, but that’s not the right thing to do for static classes, since they are never instantiated with any specific generic parameter. You need to add it to the method signature, not the class signature:So here’s your method with those two changes:
Now, what you want to do in there, you just call the validation expression. It’s a delegate, so you just call it as if it were a function, passing it the first parameter, your
MyObject, as the parameter. If it returns false, I assume the whole statement will throw an exception:You can now use it like this: