Creating Variables and Instances
Constraints on Type Parameters
Extension Methods with Generic Classes
Covariance and Contravariance in Generics
With the language constructs you've learned so far, you can build powerful objects of many different types. You do this mostly by declaring classes that encapsulate the behavior you want and then creating instances of those classes.
All the types used in the class declarations so far have been specific types—either programmer-defined or supplied by the language or the BCL. There are times, however, when a class would be more useful if you could “distill” or “refactor” out its actions and apply them not just to the data types for which they are coded but for other types as well.
Generics allow you to do just that. You can refactor your code and add an additional layer of abstraction so that, for certain kinds of code, the data types are not hard-coded. This is particularly designed for cases in which there are multiple sections of code performing the same instructions, but on different data types.
That might sound pretty abstract, so we'll start with an example that should make things clearer.
Suppose first that you have created the following code, which declares a class called MyIntStack
, which implements a stack of int
s. It allows you to push int
s onto the stack and pop them off. This, by the way, isn't the system stack.
Suppose now that you would like the same functionality for values of type float
. There are several ways you could achieve this. One way is to perform the following steps to produce the subsequent code:
MyIntStack
.MyFloatStack
.int
declarations to float
declarations throughout the class declaration.This method certainly works, but it's error-prone, and has the following drawbacks:
long
, double
, string
, and so on).With C# 2.0, Microsoft introduced the generics features, which offer more elegant ways of using a set of code with more than one type. Generics allow you to declare type-parameterized code, which you can instantiate with different types. This means you can write the code with “placeholders for types” and then supply the actual types when you create an instance of the class.
By this point in the text, you should be very familiar with the concept that a type is not an object but a template for an object. In the same way, a generic type is not a type but a template for a type. Figure 19-1 illustrates this point.
Figure 19-1. Generic types are templates for types.
C# provides five kinds of generics: classes, structs, interfaces, delegates, and methods. Notice that the first four are types, and methods are members.
Figure 19-2 shows how generic types fit in with the other types covered.
Figure 19-2. Generics and user-defined types
In the stack example, with classes MyIntStack
and MyFloatStack
, the bodies of the declarations of the classes are identical except at the positions dealing with the type of the value held by the stack.
MyIntStack
, these positions are occupied by type int
.MyFloatStack
, they are occupied by float
.You can create a generic class from MyIntStack
by doing the following:
MyIntStack
class declaration, and instead of substituting float
for int
, substitute the type placeholder T
.MyStack
.<T>
after the class name.The result is the following generic class declaration. The string consisting of the angle brackets with the T
means that T
is a placeholder for a type. (It doesn't have to be the letter T
—it can be any identifier.) Everywhere throughout the body of the class declaration where T
is located, an actual type will need to be substituted by the compiler.
Now that you've seen a generic class, let's look at generic classes in more detail and see how they're created and used.
As you know, there are two steps for creating and using your own regular, nongeneric classes: declaring the class and creating instances of the class. But generic classes are not actual classes but templates for classes—so you must first construct actual class types from them. You can then create references and instances from these constructed class types.
Figure 19-3 illustrates the process at a high level. If it's not all completely clear yet, don't worry—we'll cover each part in the following sections.
Figure 19-3. Creating instances from a generic type
Declaring a simple generic class is much like declaring a regular class, with the following differences:
For example, the following code declares a generic class called SomeClass
. The type parameters are listed between the angle brackets and then used throughout the body of the declaration as if they were real types.
There is no special keyword that flags a generic class declaration. Instead, the presence of the type parameter list, demarcated with angle brackets, distinguishes a generic class declaration from a regular class declaration.
You cannot create class objects directly from a generic class. First, you need to tell the compiler what actual types should be substituted for the placeholders (the type parameters). The compiler takes those actual types and creates a template from which it creates actual class objects.
To construct a class type from a generic class, list the class name and supply real types between the angle brackets, in place of the type parameters. The real types being substituted for the type parameters are called type arguments.
The compiler takes the type arguments and substitutes them for their corresponding type parameters throughout the body of the generic class, producing the constructed type—from which actual class instances are created.
Figure 19-4 shows the declaration of generic class SomeClass
on the left. On the right, it shows the constructed class created by using the type arguments short
and int
.
Figure 19-4. Supplying type arguments for all the type parameters of a generic class produces a constructed class from which actual class objects can be created.
Figure 19-5 illustrates the difference between type parameters and type arguments.
Figure 19-5. Type parameters versus type arguments
A constructed class type is used just like a regular type in creating references and instances. For example, the following code shows the creation of two class objects.
SomeClass
, instantiated with types short
and int
. The form is exactly analogous to the line above it, with the constructed class forms in place of a regular class name.var
keyword to make the compiler use type inference.As with nongeneric classes, the reference and the instance can be created separately, as shown in Figure 19-6. The figure also shows that what is going on in memory is the same as for a nongeneric class.
myInst
. Its value is null
.Figure 19-6. Using a constructed type to create a reference and an instance
Many different class types can be constructed from the same generic class. Each one is a separate class type, just as if it had its own separate nongeneric class declaration.
For example, the following code shows the creation of two types from generic class SomeClass
. The code is illustrated in Figure 19-7.
short
and int
.int
and long
. class SomeClass< T1, T2 > // Generic class
{
...
}
class Program
{
static void Main()
{
var first = new SomeClass<short, int >(); // Constructed type
var second = new SomeClass<int, long>(); // Constructed type
...
Figure 19-7. Two constructed classes created from a generic class
The following code shows the stack example implemented using generics. Method Main
defines two variables: stackInt
and stackString
. The two constructed types are created using int
and string
as the type arguments.
class MyStack<T>
{
T[] StackArray;
int StackPointer = 0;
public void Push(T x)
{
if ( !IsStackFull )
StackArray[StackPointer++] = x;
}
public T Pop()
{
return ( !IsStackEmpty )
? StackArray[--StackPointer]
: StackArray[0];
}
const int MaxStack = 10;
bool IsStackFull { get{ return StackPointer >= MaxStack; } }
bool IsStackEmpty { get{ return StackPointer <= 0; } }
public MyStack()
{
StackArray = new T[MaxStack];
}
public void Print()
{
for (int i = StackPointer -1; i >= 0 ; i--)
Console.WriteLine(" Value: {0}", StackArray[i]);
}
}
class Program
{
static void Main()
{
var stackInt = new MyStack<int>();
var stackString = new MyStack<string>();
stackInt.Push(3);
stackInt.Push(5);
stackInt.Push(7);
stackInt.Push();
stackString.Push("Generics are great!");
stackString.Push("Hi there!");
stackString.Print();
}
}
This code produces the following output:
Value: 7
Value: 5
Value: 3
Value: Hi there!
Value: Generics are great!
Table 19-1 summarizes some of the differences between the initial nongeneric version of the stack and the final generic version of the stack. Figure 19-8 illustrates some of these differences.
Table 19-1. Differences Between the Nongeneric and Generic Stacks
Nongeneric | Generic | |
Source Code Size | Larger: You need a new implementation for each type. | Smaller: You need only one implementation regardless of the number of constructed types. |
Executable Size | The compiled version of each stack is present, regardless of whether it is used. | Only types for which there is a constructed type are present in the executable. |
Ease of Writing | Easier to write because it's more concrete. | Harder to write because it's more abstract. |
Difficulty to Maintain | More error-prone to maintain, since all changes need to be applied for each applicable type. | Easier to maintain, because modifications are needed in only one place. |
Figure 19-8. Nongeneric stack versus generic stack
In the generic stack example, the stack did not do anything with the items it contained other than store them and pop them. It didn't try to add them, compare them, or do anything else that would require using operations of the items themselves. There's good reason for that. Since the generic stack doesn't know the type of the items it will be storing, it can't know what members these types implement.
All C# objects, however, are ultimately derived from class object
, so the one thing the stack can be sure of about the items it's storing is that they implement the members of class object
. These include methods ToString
, Equals
, and GetType
. Other than that, it can't know what members are available.
As long as your code doesn't access the objects of the types it handles (or as long as it sticks to the members of type object
), your generic class can handle any type. Type parameters that meet this constraint are called unbounded type parameters. If, however, your code tries to use any other members, the compiler will produce an error message.
For example, the following code declares a class called Simple
with a method called LessThan
that takes two variables of the same generic type. LessThan
attempts to return the result of using the less-than operator. But not all classes implement the less-than operator, so you can't just substitute any class for T
. The compiler, therefore, produces an error message.
class Simple<T>
{
static public bool LessThan(T i1, T i2)
{
return i1 < i2; // Error
}
...
}
To make generics more useful, therefore, you need to be able to supply additional information to the compiler about what kinds of types are acceptable as arguments. These additional bits of information are called constraints. Only types that meet the constraints can be substituted for the given type parameter.
Constraints are listed as where
clauses.
where
clause.where
clause, separated by commas.The syntax of a where
clause is the following:
The important points about where
clauses are the following:
where
is a contextual keyword, so you can use it in other contexts.For example, the following generic class has three type parameters. T1
is unbounded. For T2
, only classes of type Customer
, or classes derived from Customer
, can be used as type arguments. For T3
, only classes that implement interface IComparable
can be used as type arguments.
There are five types of constraints. These are listed in Table 19-2.
Table 19-2. Types of Constraints
Constraint Type | Description |
ClassName |
Only classes of this type, or classes derived from it, can be used as the type argument. |
class |
Any reference type, including classes, arrays, delegates, and interfaces, can be used as the type argument. |
struct |
Any value type can be used as the type argument. |
InterfaceName |
Only this interface, or types that implement this interface, can be used as the type argument. |
new() |
Any type with a parameterless public constructor can be used as the type argument. This is called the constructor constraint. |
The where
clauses can be listed in any order. The constraints in a where
clause, however, must be placed in a particular order, as shown in Figure 19-9.
InterfaceName
constraints.Figure 19-9. If a type parameter has multiple constraints, they must be in this order.
The following declarations show examples of where
clauses:
class SortedList<S>
where S: IComparable<S> { ... }
class LinkedList<M,N>
where M : IComparable<M>
where N : ICloneable { ... }
class MyDictionary<KeyType, ValueType>
where KeyType : IEnumerable,
new() { ... }
Unlike the other generics, a method is not a type but a member. You can declare generic methods in both generic and nongeneric classes, and in structs and interfaces, as shown in Figure 19-10.
Figure 19-10. Generic methods can be declared in generic and nongeneric types.
Generic methods have a type parameter list and optional constraints.
Note Remember that the type parameter list goes after the method name and before the method parameter list.
To invoke a generic method, supply type arguments with the method invocation, as shown here:
Figure 19-11 shows the declaration of a generic method called DoStuff
, which takes two type parameters. Below it are two places where the method is called, each with a different set of type parameters. Each of these constructed instances produces a different version of the method, as shown on the right of the figure.
Figure 19-11. A generic method with two instantiations
If you are passing parameters into a method, the compiler can sometimes infer from the types of the method parameters the types that should be used as the type parameters of the generic method. This can make the method calls simpler and easier to read.
For example, the following code declares MyMethod
, which takes a method parameter of the same type as the type parameter.
If you invoke MyMethod
with a variable of type int
, as shown in the following code, the information in the type parameter of the method invocation is redundant, since the compiler can see from the method parameter that it's an int
.
Since the compiler can infer the type parameter from the method parameter, you can omit the type parameter and its angle brackets from the invocation, as shown here:
MyMethod(myInt);
The following code declares a generic method called ReverseAndPrint
in a nongeneric class called Simple
. The method takes as its parameter an array of any type. Main
declares three different array types. It then calls the method twice with each array. The first time it calls the method with a particular array, it explicitly uses the type parameter. The second time, the type is inferred.
class Simple // Non-generic class
{
static public void ReverseAndPrint<T>(T[] arr) // Generic method
{
Array.Reverse(arr);
foreach (T item in arr) // Use type argument T.
Console.Write("{0}, ", item.ToString());
Console.WriteLine("");
}
}
class Program
{
static void Main()
{
// Create arrays of various types.
var intArray = new int[] { 3, 5, 7, 9, 11 };
var stringArray = new string[] { "first", "second", "third" };
var doubleArray = new double[] { 3.567, 7.891, 2.345 };
Simple.ReverseAndPrint<int>(intArray); // Invoke method
Simple.ReverseAndPrint(intArray); // Infer type and invoke
Simple.ReverseAndPrint<string>(stringArray); // Invoke method
Simple.ReverseAndPrint(stringArray); // Infer type and invoke
Simple.ReverseAndPrint<double>(doubleArray); // Invoke method
Simple.ReverseAndPrint(doubleArray); // Infer type and invoke
}
}
This code produces the following output:
11, 9, 7, 5, 3,
3, 5, 7, 9, 11,
third, second, first,
first, second, third,
2.345, 7.891, 3.567,
3.567, 7.891, 2.345,
Extension methods are described in detail in Chapter 7 and work just as well with generic classes. They allow you to associate a static method in one class with a different generic class and to invoke the method as if it were an instance method on a constructed instance of the class.
As with nongeneric classes, an extension method for a generic class must satisfy the following constraints:
static
.this
, followed by the name of the generic class it extends.The following code shows an example of an extension method called Print
on a generic class called Holder<T>
:
static class ExtendHolder
{
public static void Print<T>(this Holder<T> h)
{
T[] vals = h.GetValues();
Console.WriteLine("{0}, {1}, {2}", vals[0], vals[1], vals[2]);
}
}
class Holder<T>
{
T[] Vals = new T[3];
public Holder(T v0, T v1, T v2)
{ Vals[0] = v0; Vals[1] = v1; Vals[2] = v2; }
public T[] GetValues() { return Vals; }
}
class Program
{
static void Main(string[] args) {
var intHolder = new Holder<int>(3, 5, 7);
var stringHolder = new Holder<string>("a1", "b2", "c3");
intHolder.Print();
stringHolder.Print();
}
}
This code produces the following output:
3, 5, 7
a1, b2, c3
Like generic classes, generic structs can have type parameters and constraints. The rules and conditions for generic structs are the same as those for generic classes.
For example, the following code declares a generic struct called PieceOfData
, which stores and retrieves a piece of data, the type of which is determined when the type is constructed. Main
creates objects of two constructed types—one using int
and the other using string
.
This code produces the following output:
intData = 10
stringData = Hi there.
Generic delegates are very much like nongeneric delegates, except that the type parameters determine the characteristics of what methods will be accepted.
The following code shows an example of a generic delegate. In Main
, generic delegate MyDelegate
is instantiated with an argument of type string
and initialized with method PrintString
.
delegate void MyDelegate<T>(T value); // Generic delegate
class Simple
{
static public void PrintString(string s) // Method matches delegate
{
Console.WriteLine(s);
}
static public void PrintUpperString(string s) // Method matches delegate
{
Console.WriteLine("{0}", s.ToUpper());
}
}
class Program
{
static void Main( )
{
var myDel = // Create inst of delegate
new MyDelegate<string>(Simple.PrintString);
myDel += Simple.PrintUpperString; // Add a method.
myDel("Hi There."); // Call delegate
}
}
This code produces the following output:
Hi There.
HI THERE.
Since the LINQ feature of C# 3.0 uses generic delegates extensively, it's worth showing another example before we get there. I'll cover LINQ itself, and more about its generic delegates, in Chapter 21.
The following code declares a generic delegate named Func
, which takes methods with two parameters and that return a value. The method return type is represented as TR
, and the method parameter types are represented as T1
and T2
.
This code produces the following output:
Total: 28
Generic interfaces allow you to write interfaces where the formal parameters and return types of interface members are generic type parameters. Generic interface declarations are similar to nongeneric interface declarations but have the type parameter list in angle brackets after the interface name.
For example, the following code declares a generic interface called IMyIfc
.
Simple
is a generic class that implements generic interface IMyIfc
.Main
instantiates two objects of the generic class: one with type int
and the other with type string
.This code produces the following output:
5
Hi there.
The following example illustrates two additional capabilities of generic interfaces:
For example, the following code is similar to the last example, but in this case, Simple
is a nongeneric class that implements a generic interface. In fact, it implements two instances of IMyIfc
. One instance is instantiated with type int
and the other with type string
.
This code produces the following output:
5
Hi there.
When implementing an interface in a generic type, there must be no possible combination of type arguments that would create a duplicate interface in the type.
For example, in the following code, class Simple
uses two instantiations of interface IMyIfc
.
int
.There's nothing wrong in itself with the second interface, since it's perfectly fine to use a generic interface. The problem here, though, is that it allows a possible conflict, because if int
is used as the type argument to replace S
in the second interface, then Simple
would have two interfaces of the same type—which is not allowed.
Note The names of generic interfaces do not clash with nongeneric interfaces. For example, in the preceding code, we could have also declared a nongeneric interface named IMyIfc
.
As you've seen throughout this chapter, when you create an instance of a generic type, the compiler takes the generic type declaration and the type arguments and creates a constructed type. A mistake that people commonly make, however, is to assume that you can assign a delegate of a derived type to a variable of a delegate of a base type. In the following sections, we'll look at this topic, which is called variance. There are three types of variance—covariance, contravariance, and invariance.
We'll start by reviewing something you've already learned: every variable has a type assigned to it, and you can assign an object of a more derived type to a variable of one of its base types. This is called assignment compatibility. The following code demonstrates assignment compatibility with a base class Animal
and a class Dog
derived from Animal
. In Main
, you can see that the code creates an object of type Dog
and assigns it to variable a2
of type Animal
.
class Animal
{
public int NumberOfLegs = 4;
}
class Dog : Animal
{
}
class Program
{
static void Main( )
{
Animal a1 = new Animal( );
Animal a2 = new Dog( );
Console.WriteLine( "Number of dog legs: {0}", a2.NumberOfLegs );
}
}
Figure 19-12 illustrates assignment compatibility. In this figure, the boxes showing the Dog
and Animal
objects also show their base classes.
Figure 19-12. Assignment compatibility means that you can assign a reference of a more derived type to a variable of a less derived type.
Now let's look at a more interesting case by expanding the code in the following ways as shown following:
Factory
, which takes a single type parameter T
, takes no method parameters, and returns an object of type T
.MakeDog
that takes no parameters and returns a Dog
object. This method, therefore, matches delegate Factory
if we use Dog
as the type parameter.Main
creates a delegate object whose type is delegate Factory<Dog>
and assigns its reference to variable dogMaker
, of the same type.delegate Factory<Dog>
to a delegate type variable named animalMaker
of type delegate Factory<Animal>
.This second line in Main
, however, causes a problem, and the compiler produces an error message saying that it can't implicitly convert the type on the right to the type on the left.
It seems to make sense that a delegate constructed with the base type should be able to hold a delegate constructed with the derived type. So why does the compiler give an error message? Doesn't the principle of assignment compatibility hold?
The principle does hold, but it doesn't apply in this situation! The problem is that although Dog
derives from Animal
, delegate Factory<Dog>
does not derive from delegate Factory<Animal>
. Instead, both delegate objects are peers, deriving from type delegate
, which derives from type object
, as shown in Figure 19-13. Neither delegate is derived from the other, so assignment compatibility doesn't apply.
Figure 19-13. Assignment compatibility doesn't apply because the two delegates are unrelated by inheritance.
Although the mismatch of delegate types doesn't allow assigning one type to the variable of another type, it's too bad in this situation, because in the example code, any time we would execute delegate animalMaker
, the calling code would expect to have a reference to an Animal
object returned. If it returned a reference to a Dog
object instead, that would be perfectly fine since a reference to a Dog
is a reference to an Animal
, by assignment compatibility.
Looking at the situation more carefully, we can see that for any generic delegate, if a type parameter is used only as an output value, then the same situation applies. In all such situations, you would be able to use a constructed delegate type created with a derived class, and it would work fine, since the invoking code would always be expecting a reference to the base class—which is exactly what it would get.
This constant relation between the use of a derived type only as an output value, and the validity of the constructed delegate, is called covariance, and is now explicitly allowed in C# 4.0. To let the compiler know that this is what you intend, you must mark the type parameter in the delegate declaration with the out
keyword.
For example, if we change the delegate declaration in the example by adding the out
keyword, as shown here, the code compiles and works fine.
Figure 19-14 illustrates the components of covariance in this example:
T Factory<out T>()
, where type variable T
is of class Animal
.Dog
, which is derived from class Animal
.Dog
, instead of the expected object of type Animal
. The calling code can freely operate on the Animal
part of the object as it expects to do.Figure 19-14. The covariant relation allows a more derived type to be in return and out positions.
The following code illustrates a related situation. In this example, there's a delegate, named Action1
, which takes a single type parameter, and a single method parameter whose type is that of the type parameter, and it returns no value.
The code also contains a method called ActOnAnimal
, whose signature and void
return type match the delegate declaration.
The first line in Main
creates a constructed delegate using type Animal
and method ActOnAnimal
, whose signature and void return type match the delegate declaration. In the second line, however, the code attempts to assign the reference to this delegate to a stack variable named dog1
, of type delegate Action1<Dog>
.
This code produces the following output:
4
Like the previous situation, by default, you can't assign the two incompatible types. But also like the previous situation, there are situations where the assignment would work perfectly fine.
As a matter of fact, this is true whenever the type parameter is used only as an input parameter to the method in the delegate. The reason for this is that even though the invoking code passes in a reference to a more derived class, the method in the delegate is only expecting a reference to a less derived class—which of course it receives and knows how to manipulate.
This relation, allowing a more derived object where a less derived object is expected, is called contravariance and is now explicitly allowed in C# 4.0. To use it, you must use the in
keyword with the type parameter, as shown in the code.
Figure 19-15 illustrates the components of contravariance in line 2 of Main
.
void Action1<in T>(T p)
, where the type variable is of class Dog
.Animal
, which is a base class of class Dog
.Dog
, to method ActOnAnimal
, which is expecting an object of type Animal
. The method can freely operate on the Animal
part of the object as it expects to do.Figure 19-15. The contravariant relation allows more derived types to be allowed as input parameters.
Figure 19-16 summarizes the differences between covariance and contravariance in a generic delegate.
F<out T>( )
where the type variable is of a class named Base
.Derived
, which is derived from class Base
.void F<in T>(T p)
, where the type parameter is of class Derived
.Base
, which is a base class of class Derived
.Figure 19-16. A comparison of covariance and contravariance
You should now have an understanding of covariance and contravariance as it applies to delegates. The same principles apply to interfaces, including the syntax using the out
and in
keywords in the interface declaration.
The following code shows an example of using covariance with an interface. The things to note about the code are the following:
T
. The out
keyword specifies that the type parameter is covariant.SimpleReturn
implements the generic interface.DoSomething
shows how a method can take an interface as a parameter. This method takes as its parameter a generic IMyIfc
interface constructed with type Animal
.The code works in the following way:
Main
create and initialize a constructed instance of generic class SimpleReturn
, using class Dog
.IMyIfc<Animal>
. Notice several things about this declaration:
out
specifier in the interface declaration.DoSomething
with the constructed covariant class that implements the interface.This code produces the following output:
Avonlea
The previous two sections explained explicit covariance and contravariance. There is also a situation where the compiler automatically recognizes that a certain constructed delegate is covariant or contravariant and makes the type coercion automatically. That happens when the object hasn't yet had a type assigned to it. The following code shows an example.
The first line of Main
creates a constructed delegate of type Factory<Animal>
from a method where the return type is a Dog
object, not an Animal
object. In creating this delegate, the method name on the right side of the assignment operator doesn't yet have a type, and the compiler can determine that the method fits the type of the delegate except that its return type is of type Dog
rather than type Animal
. The compiler is smart enough to realize that this is a covariant relation and creates the constructed type and assigns it to the variable.
Compare that with the assignments in the third and fourth lines of Main
. In these cases, the expressions on the right side of the equals sign already have a type and therefore need the out
specifier in the delegate declaration to signal the compiler to allow them to be covariant.
class Animal { public int Legs = 4; } // Base class
class Dog : Animal { } // Derived class
class Program
{
delegate T Factory<out T>();
static Dog MakeDog() { return new Dog(); }
static void Main()
{
Factory<Animal> animalMaker1 = MakeDog; // Coerced implicitly
Factory<Dog> dogMaker = MakeDog;
Factory<Animal> animalMaker2 = dogMaker; // Requires the out specifier
Factory<Animal> animalMaker3
= new Factory<Dog>(MakeDog); // Requires the out specifier
}
}
This implicit coercion implementing covariance and contravariance has been available without the in
/out
keywords since before C# 4.0.
Other important things you should know about variance are the following:
in
and out
keywords applies only to delegates and interfaces—not classes, structs, or methods.in
or out
keyword are called invariant. These types cannot be used covariantly or contravariantly.3.22.216.254