I have method that transforms some input value by the user passing it a Func delegate wich returns the new value (very over simplified for what I am trying to achieve)
public L Coerce<L>(string value, Func<string, L> coercer)
{
return coercer(value);
}
Coerce<int>("123", v => int.Parse(v));
This is fine however I also want to be able to write methods that override the behaviour for a specific type eg…
public int Coerce<int>(string value)
{
return Coerce<int>(value, v => int.Parse(v));
}
So basically calling
Coerce<int>("123"); // equivalent Coerce<int>("123", v => int.Parse(v));
will save me having to re-write the int.Parse for every Coerce. Of course this should then extend to handle
public decimal Coerce<decimal>(string value)
{
return Coerce<decimal>(value, v => int.Parse(v));
}
Etc etc.
Can this be done neatly?
James
Well, if you really don’t want to do
Then this will do what you are asking:
Hence:
or
This will give you a compile-time error if you try to coerce to a non-convertible type, for example:
In which case you force the caller to use your
Coerce(string value, Func<string,T> coercer)overload.