Where is the Enum Generic Constraint??

by Paul Smith October 01, 2008 15:16

A frustration about the Generics framework in .NET is that it's not possible to specify a generic constraint to be any enumeration.

   1: public class SomeClassName<T> where : Enum
   2: {
   3:     // ...
   4: }

A workaround I use to enforce the constraint, although not pretty is below. Unfortunately it will not raise a build error if anyone has any better ideas please let me know.

   1: public class SomeClassName<T> where T : struct
   2: {
   3:     public SomeClassName()
   4:     {
   5:         if (!typeof(T).IsEnum)
   6:         {
   7:             throw new ArgumentException("Parameter T must be of type Enum");
   8:         }
   9:     }
  10: }

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

C#

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant