Friday, 13 March 2009

Action<T> and Func<T, TResult>

I wanted to pass a validation routine to my SetValue method that uses generics. So I used the Action delegate system.
protected void SetValue(T newValue, Action validate)
{
...
validate.Invoke(newValue);
...
}
That worked fine until I wanted to change the value (for formatting purposes). So I moved to using the Func delegate system instead. Since I want the result to be of the same type as the passed argument I used <T, T> instead of <T, TResult>.

protected T SetValue(T newValue, Func validate)
{
...
newValue = validate.Invoke(newValue);
...
}

No comments: