Not really.
If you try to use generics for this, then you'd need to also specify the type of the validator in the call to CanConvert. Here's how you'd do it:
But in your case you want to explicitly specify the type for conversion, meaning you also have to explicitly specify all the other type paramters. So these are your two options:
If you try to use generics for this, then you'd need to also specify the type of the validator in the call to CanConvert. Here's how you'd do it:
public static class MyExtensions {
public static IRuleBuilderOptions<T, string> CanConvert<T, TConvert>(this IRuleBuilder<T, string> ruleBuilder) {
return ruleBuilder.Must(value => {
var descriptor = TypeDescriptor.GetConverter(typeof(TConvert));
if(descriptor == null) return false;
return descriptor.IsValid(value);
});
}
}
...useable like this:RuleFor(x => x.Forename).CanConvert<Person, int>()
This doesn't look great, as you have to include the first type already a type parameter defined for the rule builder (the type of the object being validated). Type inference means that you can usually omit this in method calls, ie you don't have to do this all the time:RuleFor(x => x.Forename).NotNull<Person, string>();
...you can instead just do this:RuleFor(x => x.ForeName).NotNull();
...and the compiler will infer the generic types.But in your case you want to explicitly specify the type for conversion, meaning you also have to explicitly specify all the other type paramters. So these are your two options:
RuleFor(x => x.Forename).CanConvert(typeof(int));
RuleFor(x => x.Forename).CanConvert<Person, int>()