9/15/07

Why do we need "where T: enum" generic constraint

Here's an example from my code where I wish there was an "enum" generic constraint available. Basically, it is a combobox for choosing a value from enum's available values. It is automatically filled with values of the enumeration and has a strongly typed Value property.

public class Client {
// use DriveTypeCombo as a usual Combobox control
public class DriveTypeCombo : EnumSelectorCombo<DriveType> { }

...

// and use the Value property like this:
void Foo() {
driveTypeCombo1.Value = DriveType.CDRom;
}
}

public class EnumSelectorCombo<TEnum> : EnumSelectorComboBox
// where TENum : enum
{
public EnumSelectorCombo() : base(typeof(TEnum)) { }

[DesignerSerializationVisibility
(DesignerSerializationVisibility.Hidden)]
public TEnum Value {
get {
return (TEnum)Enum.Parse(
typeof(TEnum),
this.SelectedItem.ToString());
}
set {
this.SelectedItem = value.ToString();
}
}
}

public partial class EnumSelectorComboBox : ComboBox {
public EnumSelectorComboBox() : base() { }

public EnumSelectorComboBox(Type enumeration) : this() {
this.Enumeration = enumeration;
}

private Type mEnumeration;
[DesignerSerializationVisibility
(DesignerSerializationVisibility.Hidden)]
public Type Enumeration {
get {
return mEnumeration;
}
set {
if (value != null && value != mEnumeration) {
mEnumeration = value;
FillItems();
}
}
}

private void FillItems() {
this.Items.Clear();
this.Items.AddRange(Enum.GetNames(Enumeration));
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
}


kick it on DotNetKicks.com

2 comments:

Yuriy Solodkyy said...

For enum cases there is a solution with mixing C# and C++/CLI in one solution.

generic<class T> where T: Enum ref class C {
};

David Gould said...

Another poster has suggested you can use

where T: Enum

an abstract class which represents enums (similarly Int32 represents ints and do on).

http://weblogs.asp.net/kennykerr/archive/2005/05/16/The-Case-of-the-Missing-Generic-_2800_Parse-Method_2900_.aspx