You need to understand how the .NET types work for generics and how Generic .NET types differ from regular .NET types.
A couple of quick experiments can show the differences between regular .NET types and generic .NET types. When a regular .NET type is defined, it looks like the FixedSizeCollection
type defined in Example 4-1.
Example 4-1. FixedSizeCollection: a regular .NET type
public class FixedSizeCollection { /// <summary> /// Constructor that increments static counter /// and sets the maximum number of items /// and sets the maximum number of items /// and sets the maximum number of items /// </summary> /// <param name="maxItems"></param> public FixedSizeCollection(int maxItems) { FixedSizeCollection.InstanceCount++; this.Items = new object[maxItems]; } /// <summary> /// Add an item to the class whose type /// is unknown as only object can hold any type /// </summary> /// <param name="item">item to add</param> /// <returns>the index of the item added</returns> public int AddItem(object item) { if (this.ItemCount < this.Items.Length) { this.Items[this.ItemCount] = item; return this.ItemCount++; } else throw new Exception("Item queue is full"); } /// <summary> /// Get an item from the class /// </summary> /// <param name="index">the index of the item to get</param> /// <returns>an item of type object</returns> public object GetItem(int index) { if (index >= this.Items.Length && index >= 0) throw new ArgumentOutOfRangeException("index"); return this.Items[index]; } #region Properties /// <summary> /// Static instance counter hangs off of the Type for /// StandardClass /// </summary> public static int InstanceCount { get; set; } /// <summary> /// The count of the items the class holds /// </summary> public int ItemCount { get; private set; } /// <summary> /// The items in the class /// </summary> private object[] Items { get; set; } #endregion // Properties /// <summary> /// ToString override to provide class detail /// </summary> /// <returns>formatted string with class details</returns> public override string ToString() { return "There are " + FixedSizeCollection.InstanceCount.ToString() + " instances of " + this.GetType().ToString() + " and this instance contains " + this.ItemCount + " items..."; } }
FixedSizeCollection
has a static integer property variable, InstanceCount
, which is incremented in the instance constructor, and a ToString()
override that prints out how many instances of FixedSizeCollection
exist in this AppDomain.FixedSizeCollection
also contains an array of objects(Items)
, the size of which is determined by the item count passed in to the constructor. It implements methods to add and retrieve items (AddItem, GetItem)
and a read-only property to get the number of items currently in the array (ItemCount)
.
The FixedSizeCollection<T>
type is a generic .NET type with the same static property InstanceCount
field, the instance constructor that counts the number of instantiations, and the overridden ToString()
method to tell you how many instances there are of this type. FixedSizeCollection<T>
also has an Items
array property and methods corresponding to those in FixedSizeCollection
, as you can see in Example 4-2.
Example 4-2. FixedSizeCollection<T>: a generic .NET type
/// <summary> /// A generic class to show instance counting /// </summary> /// <typeparam name="T">the type parameter used for the array storage</typeparam> public class FixedSizeCollection<T> { /// <summary> /// Constructor that increments static counter and sets up internal storage /// </summary> /// <param name="items"></param> public FixedSizeCollection(int items) { FixedSizeCollection<T>.InstanceCount++; this.Items = new T[items]; } /// <summary> /// Add an item to the class whose type /// is determined by the instantiating type /// </summary> /// <param name="item">item to add</param> /// <returns>the zero-based index of the item added</returns> public int AddItem(T item) { if (this.ItemCount < this.Items.Length) { this.Items[this.ItemCount] = item; return this.ItemCount++; } else throw new Exception("Item queue is full"); } /// <summary> /// Get an item from the class /// </summary> /// <param name="index">the zero-based index of the item to get</param> /// <returns>an item of the instantiating type</returns> public T GetItem(int index) { if (index >= this.Items.Length && index >= 0) throw new ArgumentOutOfRangeException("index"); return this.Items[index]; } #region Properties /// <summary> /// Static instance counter hangs off of the /// instantiated Type for /// GenericClass /// </summary> public static int InstanceCount { get; set; } /// <summary> /// The count of the items the class holds /// </summary> public int ItemCount { get; private set; } /// <summary> /// The items in the class /// </summary> private T[] Items { get; set; } #endregion // Properties /// <summary> /// ToString override to provide class detail /// </summary> /// <returns>formatted string with class details</returns> public override string ToString() { return "There are " + FixedSizeCollection<T>.InstanceCount.ToString() + " instances of " + this.GetType().ToString() + " and this instance contains " + this.ItemCount + " items..."; } }
Things start to get a little different with FixedSizeCollection<T>
when you look at the Items
array property implementation. The Items array is declared as:
private T[] Items { get; set; }
instead of:
private object[] Items { get; set; }
The Items
array property uses the type parameter of the generic class (<T>)
to determine what type of items are allowed. FixedSizeCollection
uses object
for the Items
array property type, which allows any type to be stored in the array of items (since all types are convertible to object), while FixedSizeCollection<T>
provides type safety by allowing the type parameter to dictate what types of objects are permitted. Notice also that the properties have no associated private backing field declared for storing the array. This is an example of using the new Automatically Implemented Properties in C# 3.0. Under the covers, the C# compiler is creating a storage element of the type of the property, but you don't have to write the code for the property storage anymore if you don't have specific code that has to execute when accessing the properties. To make the property read-only, simply mark the set;
declaration private
.
The next difference is visible in the method declarations of AddItem
and GetItem
. AddItem
now takes a parameter of type T
, whereas in FixedSizeCollection
, it took a parameter of type object
. GetItem
now returns a value of type T
, whereas in FixedSizeCollection
, it returned a value of type object
. These changes allow the methods in FixedSizeCollection<T>
to use the instantiated type to store and retrieve the items in the array, instead of having to allow any object
to be stored as in FixedSizeCollection:
/// <summary> /// Add an item to the class whose type /// is determined by the instantiating type /// </summary> /// <param name="item">item to add</param> /// <returns>the zero-based index of the item added</returns> public int AddItem(T item) { if (this.ItemCount < this.Items.Length) { this.Items[this.ItemCount] = item; return this.ItemCount++; } else throw new Exception("Item queue is full"); } /// <summary> /// Get an item from the class /// </summary> /// <param name="index">the zero-based index of the item to get</param> /// <returns>an item of the instantiating type</returns> public T GetItem(int index) { if (index >= this.Items.Length && index >= 0) throw new ArgumentOutOfRangeException("index"); return this.Items[index]; }
This provides a few advantages. First and foremost is the type safety provided by FixedSizeCollection<T>
for items in the array. It was possible to write code like this in FixedSizeCollection:
// Regular class FixedSizeCollection C = new FixedSizeCollection(5); Console.WriteLine(C); string s1 = "s1"; string s2 = "s2"; string s3 = "s3"; int i1 = 1; // Add to the fixed size collection (as object). C.AddItem(s1); C.AddItem(s2); C.AddItem(s3); // Add an int to the string array, perfectly OK. C.AddItem(i1);
But FixedSizeCollection<T>
will give a compiler error if you try the same thing:
// Generic class FixedSizeCollection<string> gC = new FixedSizeCollection<string>(5); Console.WriteLine(gC); string s1 = "s1"; string s2 = "s2"; string s3 = "s3"; int i1 = 1; // Add to the generic class (as string). gC.AddItem(s1); gC.AddItem(s2); gC.AddItem(s3); // Try to add an int to the string instance, denied by compiler. // error CS1503: Argument '1': cannot convert from 'int' to 'string' //gC.AddItem(i1);
Having the compiler prevent this before it can become the source of runtime bugs is a very good thing.
It may not be immediately noticeable, but the integer is actually boxed
when it is added to the object array in FixedSizeCollection
, as you can see in the IL for the call to GetItem
on FixedSizeCollection:
IL_0170: ldloc.2
IL_0171: ldloc.s i1
IL_0173: box [mscorlib]System.Int32
IL_0178: callvirt instance int32
CSharpRecipes.Generics/FixedSizeCollection::AddItem(object)
This boxing turns the int, which is a value type, into a reference type (object)
for storage in the array. This causes extra work to be done to store value types in theobject
array.
There is a problem when you go to get an item back from the class in the FixedSizeCollection
implementation. Take a look at how FixedSizeCollection.GetItem
retrieves an item:
// Hold the retrieved string. string sHolder; // Have to cast or get error CS0266: // Cannot implicitly convert type 'object' to 'string' sHolder = (string)C.GetItem(1);
Since the item returned by FixedSizeCollection.GetItem
is of type object
, it needs to be cast to a string
in order to get what you hope is a string
for index 1. It may not be a string
—all you know for sure is that it's an object
—but you have to cast it to a more specific type coming out so you can assign it properly.
These are both fixed by the FixedSizeCollection<T>
implementation. The unboxing is addressed; no unboxing is required, since the return type of GetItem
is the instantiated type, and the compiler enforces this by looking at the value being returned:
// Hold the retrieved string. string sHolder; int iHolder; // No cast necessary sHolder = gC.GetItem(1); // Try to get a string into an int. // error CS0029: Cannot implicitly convert type 'string' to 'int' //iHolder = gC.GetItem(1);
In order to see one other difference between the two types, instantiate a few instances of each of them like so:
// Regular class FixedSizeCollection A = new FixedSizeCollection(5); Console.WriteLine(A); FixedSizeCollection B = new FixedSizeCollection(5); Console.WriteLine(B); FixedSizeCollection C = new FixedSizeCollection(5); Console.WriteLine(C); // generic class FixedSizeCollection<bool> gA = new FixedSizeCollection<bool>(5); Console.WriteLine(gA); FixedSizeCollection<int> gB = new FixedSizeCollection<int>(5); Console.WriteLine(gB); FixedSizeCollection<string> gC = new FixedSizeCollection<string>(5); Console.WriteLine(gC); FixedSizeCollection<string> gD = new FixedSizeCollection<string>(5); Console.WriteLine(gD);
The output from the preceding code shows this:
There are 1 instances of CSharpRecipes.Generics+FixedSizeCollection and this ins tance contains 0 items... There are 2 instances of CSharpRecipes.Generics+FixedSizeCollection and this ins tance contains 0 items... There are 3 instances of CSharpRecipes.Generics+FixedSizeCollection and this ins tance contains 0 items... There are 1 instances of CSharpRecipes.Generics+FixedSizeCollection'1[System.Boo lean] and this instance contains 0 items... There are 1 instances of CSharpRecipes.Generics+FixedSizeCollection'1[System.Int 32] and this instance contains 0 items... There are 1 instances of CSharpRecipes.Generics+FixedSizeCollection'1[System.Str ing] and this instance contains 0 items... There are 2 instances of CSharpRecipes.Generics+FixedSizeCollection'1[System.Str ing] and this instance contains 0 items...
The type parameters in generics allow you to create type-safe code without knowing the final type you will be working with. In many instances, you want the types to have certain characteristics, in which case you place constraints on the type (see Recipe 4.11). Methods can have generic type parameters whether the class itself does or does not.
Notice that while FixedSizeCollection
has three instances, FixedSizeCollection
, has one instance in which it was declared with bool
as the type, one instance in which int was the type, and two instances in which string
was the declaring type. This means that, while there is one .NET Type
object created for each nongeneric class, there is one .NET Type
object for every constructed type of a generic class.
FixedSizeCollection
has three instances in the example code because FixedSizeCollection
has only one type that is maintained by the CLR. With generics, one type is maintained for each combination of the class template and the type arguments passed when constructing a type instance. To make it clearer, you get one .NET type for FixedSizeCollection<bool>
, one .NET type for FixedSizeCollection<int>
, and a third .NET type for FixedSizeCollection<string>
.
The static InstanceCount
property helps to illustrate this point, as static properties of a class are actually connected to the type that the CLR hangs on to. The CLR creates any given type only once and then maintains it until the AppDomain
unloads. This is why the output from the calls to ToString()
on these objects shows that the count is three for FixedSizeCollection
(as there is truly only one of these) and between one and two for the FixedSizeCollection<T>
types.
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.