Subscribe

RSS Feed (xml)

Constrained Types in Generics

class Gen<T> {

any type can be passed to T. Thus, it is legal to create Gen objects in which T is replaced by int, double, string, FileStream, or any other type. Although having no restrictions on the type argument is fine for many purposes, sometimes it is useful to limit the types that can be passed to a type parameter. For example, you might want to create a method that operates on the contents of a stream, including a FileStream or MemoryStream. This situation seems perfect for generics, but you need some way to ensure that only stream types are used as type arguments. You don't want to allow a type argument of int, for example. You also need some way to tell the compiler that the methods defined by a stream will be available for use. For example, your generic code needs some way to know that it can call the Read( ) method.

To handle such situations, C# provides constrained types. When specifying a type parameter, you can specify a constraint that the type parameter must satisfy. This is accomplished through the use of a where clause when specifying the type parameter, as shown here:

class class-name<type-param> where type-param : constraints { // ...

Here, constraints is a comma-separated list of constraints.

There are five types of constraints:

  • You can require that a certain base class be present in a type argument by using a base class constraint. This constraint is specifi ed by naming the desired base class.

  • You can require that one or more interfaces be implemented by a type argument by using an interface constraint. This constraint is specified by naming the desired interface.

  • You can require that the type argument supply a parameterless constructor. This is called a constructor constraint. It is specified by new( ).

  • You can specify that a type argument must be a reference type by specifying the reference type constraint: class.

  • You can specify that the type argument be a value type by specifying the value type constraint: struct.

Of these constraints, the base class constraint and the interface constraint are probably the most often used, with the remaining adding fine-grained control. Each of the constraints is examined in detailed in next posts.

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail