There are a few subtleties in regard to generic types that every professional software engineer ought to know, and one of them is the code bloat that the generic types can inflict. Take the following code:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using
System;
namespace
HelloWorld
{
class
Pair<T, U>
{
public T First { get; set; }
public U Second { get; set; }
}
class
Program
{
static void Main(string[] args)
{
Pair<int, int> p1 = new Pair<int, int>() { First = 3, Second = 9 };
Pair<int, string> p2 = new Pair<int, string>() { First = 5, Second = "Marry" };
Pair<decimal, bool> p3 = new Pair<decimal, bool>() { First = 7.2M, Second = false };
Console.ReadLine();
}
}
}
|
Very simple code: a generic class with two generic types, and inside it, two properties, each of one of those generic types. Then, inside the Main() method, we create three instances of this class, using multiple combinations of types for the two generic type parameters: Pair<int, int>, Pair<int, string> and Pair<decimal, bool>.
What you should know, and should be already clear by now from the previous lessons about generics, is that each combination of these generic parameters forces the compiler to generate a new distinct class. This is only logical, we can all agree that Pair<int, int> is not equal, nor is the same type as Pair<int, string>, and I can even prove it:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using
System;
namespace
HelloWorld
{
class
Pair<T, U>
{
public T First { get; set; }
public U Second { get; set; }
}
class
Program
{
static void Main(string[] args)
{
Pair<int, int> p1 = new Pair<int, int>() { First = 3, Second = 9 };
Pair<int, string> p2 = new Pair<int, string>() { First = 5, Second = "Marry" };
Pair<decimal, bool> p3 = new Pair<decimal, bool>() { First = 7.2M, Second = false };
Console.WriteLine(p1.GetType().Equals(p2.GetType()));
Console.ReadLine();
}
}
}
|
The above code will print False at the console, because the type of p1 is definitely not the same ast the type of p2.
So, think about it: the compiler literally creates a new class for each of all the permutations of generic parameters of classes used in your codes, with all the extra codes that those classes might contain, generic-related or not. This equivalates to copy-pasting that class in slightly different versions, and you should already know how "good" copy-pasting code is. This is especially true in case of value types, because reference types benefit from a slight optimization from the compiler, but still...
As a fun homework, inspect the generated binary of the above code using a decompiling application, such as the IlSpy Visual Studio extension, and see how the compiler generated new code for each variant of your generic type parameters combinations.