
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Constraining Type Arguments
|
277
This means that the following code will compile successfully:
DisposableList<StreamReader> dl = new DisposableList<StreamReader>( );
but the following code will not:
DisposableList<string> dl = new DisposableList<string>( );
This is because the string type does not implement the IDisposable interface, and
the
StreamReader type does.
Other constraints on the type argument are allowed, in addition to requiring one or
more specific interfaces to be implemented. You can force a type argument to be
inherited from a specific base class, such as the
TextReader class:
public class DisposableList<T> : IList<T>
where T : System.IO.TextReader, IDisposable
You can also determine if the type argument is narrowed down to only value types or
only reference types. The following class declaration is constrained to using only
value types:
public class DisposableList<T> : IList<T>
where T : struct
This class declaration is constrained to only reference types:
public class DisposableList<T> : IList<T>
where T : class
In addition, you can also require any type argument to implement a public default
constructor:
public class DisposableList<T> : IList<T>
where T : IDisposable, new( )
Using constraints allows you to write generic types that accept a narrower set of
available type arguments. ...