I have never used constraints for my generic classes. So in this article I just want to show how I’ve used it:
So for now I have ICustomer interface:
and two implementations like UsualCustomer and VipCustomer.
Also I’m going to have some OrderingProcessor which is supposed to be operating with different types of Customers. But when I want to call GetOrders method I just have not it in my list, like below:
but once I’ve changed the declaration of the OrderingProcess just a little bit, with specifying type of T
World has smiled to me and I’m getting what I want, please see:
I expect that you are laughing while reading this post. Maybe because this thing is too simple to write article/post on it if you are familiar with C#/.NET. Yes, but I have never tried it myself. Did you?
To make you laughing not so much loud let us take a look on another architecture:
As you see we can create specific VipOrderingProcessor and we are constraining it to use just VipCustomers or derived classes. This gives us opportunity to specify constraints on different levels of implementation.
But do you know what does another constraint new() mean?
This constraint specifies that TCustomer objects will have public default constructor, so you can write
var vipCustomer = new TCustomer();
This could be very useful for implementing Factory Design Pattern. I’m sure that next time I will need to develop whole family of Factories I will use constraints, since code could be much flexible in this case.
code
more code
~~~~