Many articles I’ve read about generic classes show a very simple implementation that can sum 2 numbers, output the type passed in or something similar. These are useful articles for basic understanding of how to get started with generic classes, but I am going to go a step further by showing a real world example of them.

We are going to create a generic credit card processing class that accepts request and response types that only implement a specific interface which will be instantiated by a factory method.

First lets start of with the core objects that our solution will require. These are the request and response objects, and they are kept small for prototyping.

This is the core factory implementation that will return the appropriate PaymentGateway object. Notice that there are 2 generic parameters(T1 and T2) that are required when instantiating this object. As the syntax states, they must both implement the interfaces entered after the where clause constraints.

Once the factory above returns a PaymentGateway object, we can simply use the methods since the GetPaymentProcessor factory method already instantiated it using the generic types we provided when initially creating the factory. We are going to reach out to a mock service that returns a hard coded token.

Here is a test method that demonstrates all of the functionality from above.

A great benefit to this architecture is that it allows you to support an unlimited amount of PaymentGateways as long as they implement the IPaymentGateway interface and their request and response objects implement the IPaymentRequest and IPaymentResponse interfaces.

I have left out all the interfaces in favor of focusing only on the concrete objects in this article. You can view the entire functional project on Github here

Happy Coding!