Home > .NET Framework > CLR Generics – Constraints

CLR Generics – Constraints

Generic Constraints
Generic type parameters can be constrained. Assume we want to write an encryption algorithm using a generic type.

public class EncryptionHelper {
...
}

Here we want all the type parameters to inherit from the System.IO.Stream class. How can this be done? Generic type parameters can be constrained. Assume we want to write an encryption algorithm using a generic type.

public class EncryptionHelper {
	public T Encrypt(T stream) {
		stream.Open(); // Error
	}
}

Error object class doesn’t have a Open method. Can this be a solution?

public class EncryptionHelper {
	public T Encrypt(T stream) {
		Stream streamType = (Stream)T; // Error
		...
	}
}

This will work.

public class EncryptionHelper {
	public T Encrypt(T stream) {
		Stream streamType = (Stream)((Object)T); 
		streamType.Open();
		...
	}
}

But what about the type safety which generics promised? The client can pass instance of any class to this method. The actual solution is to use constraints.

public class EncryptionHelper where T:System.IO.Stream {
	public T Encrypt(T stream) {
		stream.Open(); // Error
	}
}

The where clause is used to specify a constraint that the type parameter has to inherit from Stream class. The compiler can check for these calls. This is called a primary constraint. There are two special primary consraints ‘struct’, ‘class’ which specify whether the type argument has to be a value type or reference type. The primary constraint can specify at the most one non sealed type. This type cannot be an enum or a delegate. In addition using a constraint you also specify a zero or more interfaces a type parameter has to comply with. This is called a secondary constraint. In addition to primary and seondary constraints you can specify a type to have a default parameterless constructor. This is called a constructor constraint, specified like "…where T : new() …".

Advertisements
Categories: .NET Framework
  1. No comments yet.
  1. November 19, 2010 at 11:00 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: