says: "mastering the skills to maximize the tools"

C# Generic Constraints

March 28th, 2008

Generic is a new wonder in .NET with the flexiblity it introduces to coders. But when you wish to explore further, you might face the limitation of only able to work with Object capabilities. This is because generic doesn’t know your type details, and since all types are Object, so you only have Object to play with. To overcome this, we have Where keyword in C# (VB.net has As, i think). Apart from be able to constraint the types that generic accept, it also allows you to use the constraints capabilities.

Generics support few types of constraints:

  • Interface: Allow only types that implement specific interfaces to use your generic.
  • Class/Base class: Allow only types that match or inherit from a specific base class to use your generic.
  • Constructor: Require types that use your generic to implement a parameterless constructor.

Say you have a custom Interface as below

public interface IMyCustomOne
{
	string WhatsMyName();
}

and a generic method

public bool CheckNameEqualJohn<T>()
{
	return (T.WhatsMyName == "John");
}

Compiler will throw you at the instant you try to build.

To solve this, we add Where at the end

public bool CheckNameEqualJohn<T>() where T : IMyCustomOne
{
	return (T.WhatsMyName == "John");
}

Woots, compiler is now happy! The obstacle has been removed and off you go to maximize your creativity. If you need 2 constraints, how to go about it?

public class MyClass<T,U>
	where T : IMyCustomT
	where U : IMyCustomU
{
	//....
}

Some additional jargons about this constraint that will make you look cooler in front of your peers

Unbound Type Parameter
Basically this refers to the most basic way of us using generic

public class MyClass<T>
{
	//....
}

Naked Type Constraint
When a generic type parameter is used as constraint

public class MyClass<T>
{
	public void MethodOne<U>(U param) where U : T
	{
		//....
	}
}

Happy Generic’ing!

Post a Comment