Consider this generic class:
public class Request<TOperation>
where TOperation : IOperation
{
private TOperation _operation { get; set; }
public string Method { get { return _operation.Method; } }
public Request(TOperation operation)
{
_operation = operation;
}
}
What real benefits does the generic version above offer over this non-generic version below?
public class Request
{
private IOperation _operation { get; set; }
public string Method { get { return _operation.Method; } }
public Request(IOperation operation)
{
_operation = operation;
}
}
The IOperation interface is:
public interface IOperation
{
string Method { get; }
}
With the generic version a method could take a parameter of type
Request<FooOperation>. Passing in an instance ofRequest<BarOperation>would be invalid.So, the generic version enables methods to ensure they get a request for the correct operation.