I built a extension method for Enums (Enumerations) – , name it, say GetEnumSecondName
static string GetEnumSecondName(this Enum myEnumInstance) {...}
Now, I have a generic method, that should take a Enumeration and return all the second names for that type.
List<string> GetSecondNames<T : ?T:Enum ? >()
{
// ...
foreach T member in GetAllMembers<T>()
// should work only for Enum instances
resultList.Add(member.GetEnumSecondName());
// ...
}
Is there a workaround to do it?
Edit:
As I understood (thanks to Jon Skeet), C# does not support thins kind of constraint. If there are any VB.NET expert to confirm that “ordinary” VB.NET does not support it either. Thanks.
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:
And the compiler complains with:
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:
ConstraintChanger\Program.cs. In particular, check in\Program Files\Microsoft SDKs\Windowsto see what version you’ve got – and change Program.cs appropriatelylib)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…