Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to constraint a generic to be of type enum?

Consider the following code:

class Base<T>
{
 //Base members
}

I want the generic T to be an enum (using constraints if possible). How can I do this in C#?

EDIT:
Using code contracts -introduced by Akash Kava- also seems like a nice way. I managed to get it to produce a run time error which is useless. Here's the code I tried. It should be possible to generate a compile time warning but I can't get it to work.

like image 334
atoMerz Avatar asked Dec 31 '11 16:12

atoMerz


2 Answers

This is supported at the IL level but not in C#. You may take a look at unconstrained melody written by Jon Skeet which allows you to achieve that. And here's the corresponding blog post where he explains in details.

like image 139
Darin Dimitrov Avatar answered Oct 01 '22 06:10

Darin Dimitrov


.NET 4.0 onwards you can create warnings by using Code Contracts, http://msdn.microsoft.com/en-us/devlabs/dd491992, this will let you check some preconditions and display warnings to developer.

like image 31
Akash Kava Avatar answered Oct 01 '22 06:10

Akash Kava