Sep 4, 2012

C#/.Net Generic constraints

Hi

Despite having no doubt about the usefulness of type constraints in C# generics (this is a key feature to help avoiding bugs when writing generic code in C#) I always had  the impression that it should be able to express more constraints than what the C# language / compiler exposes.

Well, some
 time ago this blog entry called my attention on my RSS reader and motivated me to go and scan the .Net specification (more specifically § II.10.1.7 in the CLI Metadata Definition and Semantics document which can be downloaded from here) and to my surprise I found out that in addition to the valid C# generic constraints CLI also support constraining a generic argument to delegates, arrays and even enums! That is nice.

Next question is: does the C# compiler abides by these rules when consuming assemblies?


To answer this question I wrote a small class library (
in C#) that exposes some generic types and manually (ildasm/ilasm) added each of these constraints. After that I created one application (C#) that uses this library and confirmed that C# compiler does respect these constraints (at least in VS 2010 which uses CSC 4.0.30319.1). Bellow you can see the result of trying to use these generic types with incompatible types:
Generic parameter 'E' was constrained to enums
Generic parameter 'E' was constrained to enums

Generic parameter 'A' was constrained to arrays. 
You can download the sample application from here.

The bottom line:  Generic constrains in .Net  are more useful than what you may be lead to believe ;)

As always, don't be shy! Let me know what you think.

Hope you find this useful.

No comments: