Have you ever thought of dynamically defining class variable type?
Or maybe define Method argument type during execution? If yes, and you still have no idea how to do it, you've come to the right place. Ladies and gentlemen, I'd like to introduce to you our hero - C# generics.
But before the C# generics comes into action, let's see how our old non-generic friend is doing.
Mr Item, can you enter?
Well, as you can see Mr. Item consists of 2 variables: price of int type, and description of string type.
But hold on a second. What if we'd like to have price represented by double? Assuming that as well we'd like to use
items whose price is int? The answer, as you've might have guessed, is fairly simple.
Miss Generic Item, can you enter ?(yes yes Mr. Item, you're free to go now).
Ok, now let us give an instance of Miss Generic Item class. Ready?
So, here it goes:
Whoa! Whatdya say? Let's try int instead of double:
Got the point? You can use Miss Generic Item as a template. You're not limited to any particular
variable type. What do you want? An int? String? Float? Bool? 'Please, feel free to fill me with
anything you want', said Miss Generic Item.
And now, let's try defining class that operates only on the generic types.
Class main purpose will be to compare two variables of any type, and return smaller/larger:
I bet you're asking yourself by now 'How the hell am I supposed to use it?':
Okay, now let's get back to block /* logic for comparing omitted */.
How do we compare 2 items of unknown type? It's even easier than you may think.
We'll have to modify our Comparer class, and add one condition:
This way we can cast Type to IComparable interface, that forces Type to implement
certain methods, in our case 'int CompareTo(object obj)', which compares object that
implements IComparable with any other object.
So, our simple GetLarger() method will look this way:
Of course this is just as simple as possible, and equality of arg1 and arg2 is omitted. In such case the arg1 will be returned.
Ok, so, basically, this is all you have to know in order to start using C# generics, fairly simple, isn't it?
And in simplicity lies hidden power. Imagine - today you're gonna gain better control of your code, and tomorrow, tomorrow Pinkie,
you're gonna conquer the world ;)
PS. No animals were harmed during writing this tutorial.
PS2. Miss generic Item, and mister Item will get married 5 years later, and live long and happily util mister Item dies.