473,396 Members | 1,755 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Enum as a Generics constraint - why doesn't it work?


Hi Group.

I would like to do the following:
public static DecriptiveCollection GetValuesForDisplay<T>() where T :
System.Enum
{
DecriptiveCollection list = new DecriptiveCollection ();
foreach(T value in Enum.GetValues(typeof(T)))
{
// add description Attributes and enum values to collection
}
return list;
}
But I recieve an "Contstraint cannot be special class Enum" - compile error
....
- why is this?

Regards, Rune

Mar 26 '06 #1
7 19655
>- why is this?

Even if it was possible, it wouldn't work the way you probably want.
In addition to actual enum types, you would be able to specify
System.Enum itself (which isn't an enum).
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 26 '06 #2
This is by design and it has been mentioned in the specification.

C#2.0 Specification

http://download.microsoft.com/downlo...cification.doc

A class-type constraint must satisfy the following rules:

The type must be a class type.
The type must not be sealed.
The type must not be one of the following types: System.Array,
System.Delegate, System.Enum, or System.ValueType.
The type must not be object. Because all types derive from object, such
a constraint would have no effect if it were permitted.
At most one constraint for a given type parameter can be a class type.

Mar 26 '06 #3

"Mattias Sjögren" <ma********************@mvps.org> wrote:
- why is this?


Even if it was possible, it wouldn't work the way you probably want.
In addition to actual enum types, you would be able to specify
System.Enum itself (which isn't an enum).


Yeah, I guess there's a reason for the Type.IsEnum property.

- It would still be nice to have the compile-time verification of the Types
you pass in to such a method though ...

R-)
Mar 26 '06 #4
"Rune B" <ye*******@bingo.com> a écrit dans le message de news:
ex**************@TK2MSFTNGP12.phx.gbl...

| public static DecriptiveCollection GetValuesForDisplay<T>() where T :
| System.Enum
| {
| DecriptiveCollection list = new DecriptiveCollection ();
| foreach(T value in Enum.GetValues(typeof(T)))
| {
| // add description Attributes and enum values to collection
| }
| return list;
| }
|
|
| But I recieve an "Contstraint cannot be special class Enum" - compile
error

Why do you need to use generics ?

void PrintEnum(Enum e)
{
Array a = Enum.GetValues(e.GetType());
foreach (object o in a)
...
}

....or you could do something devious like this :

void PrintEnum<T>(Enum e)
{
Array a = Enum.GetValues(typeof(T));
foreach (T o in a)
...
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Mar 26 '06 #5

"Joanna Carter [TeamB]" <jo****@not.for.spam> wrote:
Why do you need to use generics ?

void PrintEnum(Enum e)
{
Array a = Enum.GetValues(e.GetType());
foreach (object o in a)
...
}

...or you could do something devious like this :

void PrintEnum<T>(Enum e)
{
Array a = Enum.GetValues(typeof(T));
foreach (T o in a)
...
}


I guess I don't *need* generics, I just like them ;-)
- and the constraint they can give you at compiletime.

- I ended up doing something similar to your first example.

R-)
Mar 26 '06 #6
> where T : System.Enum
...
But I recieve an "Contstraint cannot be special class Enum" - compile error
....
- why is this?


The language spec does not allow this - you cannot restrict to Delegate
either (another common thing people want to do).

You can put a test in the static constructor to enforce that the Type of T
is Enum, but it will be a runtime check.

Mark
Mar 26 '06 #7
The thing about constraints is that the name is misleading - they were
actually added not constrain the user of a class but to remove constraints
on the implementor the class!

The point of a constraint is to allow access to methods and properties of an
object of parameterized type without casting but since Enum adds nothing to
Object (all the interesting methods are static) it isn't allowed.

This seems to be a common policy in C# - whatever seems unnecessary or
redundant is explicitly prohibited - and in many cases they have carried it
too far. Personally I think you should be allowed to write stuff like "where
T: object" if you want - what's the harm? And in the case of enums I agree
that there are cases where it would be useful.

"Rune B" <ye*******@bingo.com> wrote in message
news:ex**************@TK2MSFTNGP12.phx.gbl...

Hi Group.

I would like to do the following:
public static DecriptiveCollection GetValuesForDisplay<T>() where T :
System.Enum
{
DecriptiveCollection list = new DecriptiveCollection ();
foreach(T value in Enum.GetValues(typeof(T)))
{
// add description Attributes and enum values to collection
}
return list;
}
But I recieve an "Contstraint cannot be special class Enum" - compile
error ...
- why is this?

Regards, Rune

Mar 27 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Wiktor Zychla | last post by:
I've read several documents about upcoming C# generics and I still cannot understand one thing. Would it be valid to write a code like this: class SomeClass { public void AMethod<T>(T a, T...
21
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
10
by: Ruediger Klaehn | last post by:
Sorry about the harsh language, but I have to vent my anger to somebody who actually understands what I am talking about. Complaining to my girlfriend is not going to produce any meaningful results...
31
by: Michael C | last post by:
If a class inherits from another class, say Form inherits from control, then I can assign the Form to a variable of type Control without needing an explicit conversion, eg Form1 f = new Form1();...
4
by: Tom Jastrzebski | last post by:
Hello everybody, Here is the problem I came across experimenting with Generics. I would like to write a class or a struct adding integer to any other, initially undefined *numeric type*. So, my...
17
by: atgraham | last post by:
Here is the "lead C# architect" attempting to impugn C++ templates (bottom of the page). http://www.artima.com/intv/generics2.html (bottom of the page) (Full article begins at...
34
by: Steven Nagy | last post by:
So I was needing some extra power from my enums and implemented the typesafe enum pattern. And it got me to thinking... why should I EVER use standard enums? There's now a nice little code...
6
by: =?Utf-8?B?UXVhbiBOZ3V5ZW4=?= | last post by:
I am trying to create a generics class with multiple constrains, as follows: public class KeyHandler<Twhere T : TextBoxBase, ComboBox When I try that, the compiler would complain: The class...
4
by: codefragment | last post by:
Hi The methods below are identical except they take as arguments different enum types. There must be a better way of writing this? ta public string ConcatValues(params EnumType1 types) {
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.