Yes, there's a workaround. You may not like it though. You have to rewrite the IL to express the constraint you want - because the CLR allows it, but C# doesn't. (The compiler respects the constraint; it just doesn't let you express it in C# code.)
I have a project called Unconstrained Melody which does exactly this, introduced in a blog post.
It's regrettable that you can't express this, and maybe it'll be fixed in a future version of the language. For now, IL rewriting is all there is as far as I know.
EDIT: I've just tried the constraint you'd want in VB:
Foo(Of T As { System.Enum, Structure }) (...)
And the compiler complains with:
error BC32061: 'Enum' cannot be used as a type constraint.
So no, you can't do it in VB either. Oddly enough, the web page about that error doesn't mention the restriction...
EDIT: To anyone wanting to play with Unconstrained Melody, there are a few steps required to get it working:
- You need to make sure you have an appropriate SDK directory as referred to by
ConstraintChanger\Program.cs
. In particular, check in \Program Files\Microsoft SDKs\Windows
to see what version you've got - and change Program.cs appropriately
- Critically, you need a directory called "Rewritten" at the top level (i.e. alongside
lib
)
- If you're using VS2010 you'll need to go through the project upgrade at the start
Once all of that is correct, you should just be able to hit Ctrl-Shift-B and get a working build. Do not remove and replace the project references - the test assembly needs to refer to the rewritten one, not the project it's created from.
I'll attempt to address some of these issues tonight - and possibly even create a Nuget package...