Microsoft Visual C# Step by Step (Developer Reference) by John Sharp

Microsoft Visual C# Step by Step (Developer Reference) by John Sharp

Author:John Sharp [Sharp, John]
Language: eng
Format: azw3, epub
Publisher: Pearson Education
Published: 2015-10-28T04:00:00+00:00


* * *

Note

Only interface and delegate types (which are covered in Chapter 18) can be declared as covariant. You do not specify the out modifier with generic classes.

* * *

Contravariant interfaces

Contravariance follows a similar principle to covariance except that it works in the opposite direction; it enables you to use a generic interface to reference an object of type B through a reference to type A as long as type B derives from type A. This sounds complicated, so it is worth looking at an example from the .NET Framework class library.

The System.Collections.Generic namespace in the .NET Framework provides an interface called IComparer, which looks like this:

Click here to view code image

public interface IComparer<in T>

{

int Compare(T x, T y);

}

A class that implements this interface has to define the Compare method, which is used to compare two objects of the type specified by the T type parameter. The Compare method is expected to return an integer value: zero if the parameters x and y have the same value, negative if x is less than y, and positive if x is greater than y. The following code shows an example that sorts objects according to their hash code. (The GetHashCode method is implemented by the Object class. It simply returns an integer value that identifies the object. All reference types inherit this method and can override it with their own implementations.)

Click here to view code image

class ObjectComparer : IComparer<Object>

{

int IComparer<Object>.Compare(Object x, Object y)

{

int xHash = x.GetHashCode();

int yHash = y.GetHashCode();



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.