I know this rather goes against the idea of enums, but is it possible to extend enums in C#/Java? I mean "extend" in both the sense of adding new values to an enum, but also in the OO sense of inheriting from an existing enum.
I assume it's not possible in Java, as it only got them fairly recently (Java 5?). C# seems more forgiving of people that want to do crazy things, though, so I thought it might be possible some way. Presumably it could be hacked up via reflection (not that you'd every actually use that method)?
I'm not necessarily interested in implementing any given method, it just provoked my curiosity when it occurred to me :-)
The reason you can't extend Enums is because it would lead to problems with polymorphism.
Say you have an enum MyEnum with values A, B, and C , and extend it with value D as MyExtEnum.
Suppose a method expects a myEnum value somewhere, for instance as a parameter. It should be legal to supply a MyExtEnum value, because it's a subtype, but now what are you going to do when it turns out the value is D?
To eliminate this problem, extending enums is illegal
You're going the wrong way: a subclass of an enum would have fewer entries.
In pseudocode, think:
enum Animal { Mosquito, Dog, Cat };
enum Mammal : Animal { Dog, Cat }; // (not valid C#)
Any method that can accept an Animal should be able to accept a Mammal, but not the other way around. Subclassing is for making something more specific, not more general. That's why "object" is the root of the class hierarchy. Likewise, if enums were inheritable, then a hypothetical root of the enum hierarchy would have every possible symbol.
But no, C#/Java don't allow sub-enums, AFAICT, though it would be really useful at times. It's probably because they chose to implement Enums as ints (like C) instead of interned symbols (like Lisp). (Above, what does (Animal)1 represent, and what does (Mammal)1 represent, and are they the same value?)
You could write your own enum-like class (with a different name) that provided this, though. With C# attributes it might even look kind of nice.
When built-in enums aren't enough, you can do it the old fashion way and craft your own. For example, if you wanted to add an additional property, for example, a description field, you could do it as follows:
public class Action {
public string Name {get; private set;}
public string Description {get; private set;}
private Action(string name, string description) {
Name = name;
Description = description;
}
public static Action DoIt = new Action("Do it", "This does things");
public static Action StopIt = new Action("Stop It", "This stops things");
}
You can then treat it like an enum like so:
public void ProcessAction(Action a) {
Console.WriteLine("Performing action: " + a.Name)
if (a == Action.DoIt) {
// ... and so on
}
}
The trick is to make sure that the constructor is private (or protected if you want to inherit), and that your instances are static.
Enums are supposed to represent the enumeration of all possible values, so extending rather does go against the idea.
However, what you can do in Java (and presumably C++0x) is have an interface instead of a enum class. Then put you standard values in an enum that implements the feature. Obviously you don't get to use java.util.EnumSet and the like. This is the approach taken in "more NIO features", which should be in JDK7.
public interface Result {
String name();
String toString();
}
public enum StandardResults implements Result {
TRUE, FALSE
}
public enum WTFResults implements Result {
FILE_NOT_FOUND
}
You can use .NET reflection to retrieve the labels and values from an existing enum at run-time (Enum.GetNames() and Enum.GetValues() are the two specific methods you would use) and then use code injection to create a new one with those elements plus some new ones. This seems somewhat analagous to "inheriting from an existing enum".
I didn't see anyone else mention this but the ordinal value of an enum is important. For example, with grails when you save an enum to the database it uses the ordinal value. If you could somehow extend an enum, what would be the ordinal values of your extensions? If you extended it in multiple places how could you preserve some kind of order to these ordinals? Chaos/instability in the ordinal values would be a bad thing which is probably another reason why the language designers have not touched this.
Another difficulty if you were the language designer, how can you preserve the functionality of the values() method which is supposed to return all of the enum values. What would you invoke this on and how would it gather up all of the values?
Adding enums is a fairly common thing to do if you go back to the source code and edit, any other way (inheritance or reflection, if either is possible) is likely to come back and hit you when you get an upgrade of the library and they have introduced the same enum name or the same enum value - I have seen plenty of lowlevel code where the integer number matches to the binary encoding, where you would run into problems
Ideally code referencing enums should be written as equals only (or switches), and try to be future proof by not expecting the enum set to be const
If you mean extends in the Base class sense, then in Java... no.
But you can extend an enum value to have properties and methods if that's what you mean.
For example, the following uses a Bracket enum:
class Person {
enum Bracket {
Low(0, 12000),
Middle(12000, 60000),
Upper(60000, 100000);
private final int low;
private final int high;
Brackets(int low, int high) {
this.low = low;
this.high = high;
}
public int getLow() {
return low;
}
public int getHigh() {
return high;
}
public boolean isWithin(int value) {
return value >= low && value <= high;
}
public String toString() {
return "Bracket " + low + " to " + high;
}
}
private Bracket bracket;
private String name;
public Person(String name, Bracket bracket) {
this.bracket = bracket;
this.name = name;
}
public String toString() {
return name + " in " + bracket;
}
}
Saw a post regarding this for Java a while back, check out http://www.javaspecialists.eu/archive/Issue161.html .
I would like to be able to add values to C# enumerations which are combinations of existing values. For example (this is what I want to do):
AnchorStyles is defined as
public enum AnchorStyles {
None = 0,
Top = 1,
Bottom = 2,
Left = 4,
Right = 8,
}
and I would like to add an AnchorStyles.BottomRight = Right + Bottom so instead of saying
my_ctrl.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
I can just say
my_ctrl.Anchor = AnchorStyles.BottomRight;
This doesn't cause any of the problems that have been mentioned above, so it would be nice if it was possible.
A temporary/local workaround, when you just want very local/one time usage:
enum Animals { Dog, Cat }
enum AnimalsExt { Dog = Animals.Dog, Cat= Animals.Cat, MyOther}
// BUT CAST THEM when using:
var xyz = AnimalsExt.Cat;
MethodThatNeedsAnimal( (Animals)xyz );
See all answers at: Enum "Inheritance"
You can't inherit from/extend an enum, you can use attributes to declare a description. If you're looking for an integer value, that's built-in.
Hmmm - as far as I know, this can't be done - enumerations are written at design-time and are used as a convenience to the programmer.
I'm pretty sure that when the code is compiled, the equivalent values will be substituted for the names in your enumeration, thereby removing the concept of an enumeration and (therefore) the ability to extend it.
Some time back even i wanted to do something like this and found that enum extensions would voilate lot of basic concepts... (Not just polymorphisim)
But still u might need to do if the enum is declared in external library and
Remember you should make a special caution when using this enum extensions...
public enum MyEnum { A = 1, B = 2, C = 4 }
public const MyEnum D = (MyEnum)(8);
public const MyEnum E = (MyEnum)(16);
func1{
MyEnum EnumValue = D;
switch (EnumValue){
case D: break;
case E: break;
case MyEnum.A: break;
case MyEnum.B: break;
}
}
As far as java is concerned it is not allowed because adding elements to an enum would effectively create a super class rather than a sub class.
Consider:
enum Person (JOHN SAM}
enum Student extends Person {HARVEY ROSS}
A general use case of Polymorphism would be
Person person = Student.ROSS; //not legal
which is clearly wrong.
Related
If I have a method parameter that is an enum, intellisense will pick up the possible values for this enum and let me pick one. This isn't ideal for me however as it's possible people might want to use values outside of my defined set. If I make my argument a byte instead, I can then create a static class filled with consts that hold my defined set of values - the only downside is that intellisense does not know about this library of values. Is there a way to point intellisense towards a range of 'helper' values?
Technically you can assign 'invalid' values to your enum. Since the backing store of an enum is an int, you can assign any value to it:
public enum X
{
A = 0,
B = 1
}
class Program
{
static void Main(string[] args)
{
X x = (X)2;
}
}
That way, you can still have the IntelliSense support, and allow off-values. Of course, this has drawbacks too, so you have to consider whether they outweigh the pros.
A fix for that could be to assign 'custom' values in your enum, which you reserve for use later on:
public enum X
{
A = 0,
B = 1,
Custom1 = 2
}
To directly answer the Intellisense part of you question, then no I don't think it is possible to do that.
However I think you can solve your problem by using function overloading, this way you can use either type and have the benefits of both:
void Myfunction(MyEnum e)
{
MyFunction((byte)e);
}
void MyFunction(byte b)
{
// Do something
}
I've searched and tried many things but I'm not really fully happy.
While converting an old project from VB.Net to C# I found that the behaviour between the 2 languages is very different and breaks the logic in C# if not dealt with.
Consider an enum like:
public enum TestEnum
{
Val1 = 1,
Val2 = 2
}
I have this code in VB.Net
// Will contain 1
txthMyHiddenField.Value = TestEnum1.Val1
And also
// Will contain ~/Something?var=1
Dim Url As String = "~/Something?var=" & TestEnum1.Val1
In C# this would have the first case having Val1 and on the second case "~/Something?var=Val1"
The solution so far I could come up with without redesigning lots of code is to go everywhere and do something like:
= myEnum.ToString("d");
// Or
= ((int)myEnum).ToString();
// Or an extension.
I also considered creating an enum "class" but then I would have to change all switch statements, which is an even worse solution.
Am I missing something? Is there a cleaner way?
Why not simply
var url = "~/Somethimg?var=" + (int)myEnum;
For what it's worth, maybe this extension helps:
public static class EnumExtensions
{
public static int AsInt<TEnum>(this TEnum enumType) where TEnum : struct, IConvertible
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an enum type");
return ((IConvertible)enumType).ToInt32(null);
}
}
var url = "~/Somethimg?var=" + myEnum.AsInt();
#Rivers,
I added a comment requesting more info in #Tim Schmelter's post but will try to provide a solution in the mean time.
#Eric, is correct in that it appears to come down to the explicit nature of C#. I also agree with #THG that if there is any change of repeatedly requiring this conversion, then an extension method is the cleanest way to go.
I haven't found a way to explicitly filter for enum, so I would be very interested in how such an extension method could be implemented.
In my case, I have limited type filtering and perform runtime validation. (I would obviously prefer compile time):
public static string ToIntString<T>(this T enumVal) where T : struct, IConvertible, IComparable, IFormattable
{
TestGenericEnum<T>();
return (Convert.ToInt32(enumVal).ToString();
}
private static void TestGenericEnum<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be of type System.Enum");
}
Update: Tossed in IComparable, IFormattable restrictions per #Preston's advice.
Update 2: Bone headed move, can't cast int directly, need to use Convert class.
Assume i have an enumeration:
namespace System.Windows.Forms
{
public enum DialogResult { None, OK, Cancel, Abort, Retry, Ignore, Yes, No }
}
i want to declare a "set" made up of these enumerated types
ShowForm(Form frm, DialogResults allowedResults)
In other languages you would declare:
public DialogResults = set of DialogResult;
And then i can use
ShowForm(frm, DialogResult.OK | DialogResult.Retry);
C# has the notion of Flags, pseudocode:
[Flags]
public enum DialogResults { DialogResult.None, DialogResult.OK, DialogResult.Cancel, DialogResult.Abort, DialogResult.Retry, DialogResult.Ignore, DialogResult.Yes, DialogResult.No }
problem with that it's not real code - Flags does not instruct the compiler to create a set of flags.
in one case the type should only allow one value (DialogResult)
in another case the type should allow multiple values of above (DialogResults)
How can i have a "set" of enumerated types?
Note: i assume it's not possible in C#. If that's the answer: it's okay to say so - the question is answered.
Note: Just because i believe C# language doesn't have the feature doesn't mean it doesn't have the feature - i may just not have found it yet.
Update: another example:
Assume i have an enumeration:
public enum PatronTier
{
Gold = 1,
Platinum = 2,
Diamond = 3,
SevenStar = 7 //Yes, seven
}
i want to declare a "set" made up of these enumerated types
public Tournament
{
public PatronTiers EligibleTiers { get; set; }
}
In other languages you would declare:
public PatronTiers = set of PatronTier;
And then i can use:
tournament.EligibleTiers = PatronTier.Gold | PatronTier.SevenStar;
C# has the notion of Flags, pseudocode:
[Flags]
public enum PatronTiers { PatronTier.Gold, PatronTier.Platinum, PatronTier.Diamond, PatronTier.SevenStar }
problem with that it's not real code.
How can i have a "set" of enumerated types?
Seems like you want an array of things. There are array types in C#, but nothing that is directly equivalent to your examples in terms of compiler support, closest is perhaps DialogResults[], an array of DialogResults.
Try supplying a HashSet of the items you allow. HashSet<T> implements ISet<T>, and it's usually best to work against interfaces than concrete types, especially for method signatures:
ShowForm(Form frm, ISet<DialogResults> allowedResults);
Then you can use Contains to test for items:
if (allowedResults.Contains(DialogResults.OK))
{
}
Somewhat pointless alternative: you could always implement your own Set<Enum> type using Jon Skeet's Unconstrained Melody to give you a nicer syntax from the perspective of the caller and get a little closer to your examples.
I don't suppose you just mean using something like this?
var DialogResults = Enum.GetValues(typeof(DialogResult));
with a .Select(dr => (DialogResult)dr).ToArray() if you want it strongly typed.
I think you want something like this:
foreach (var item in System.Enum.GetValues(typeof(PatronTier)))
{
Console.WriteLine(item);
}
What is main use of Enumeration in c#?
Edited:-
suppose I want to compare the string variable with the any enumeration item then how i can do this in c# ?
The definition in MSDN is a good place to start.
An enumeration type (also named an
enumeration or an enum) provides an
efficient way to define a set of named
integral constants that may be
assigned to a variable.
The main benefit of this is that constants can be referred to in a consistent, expressive and type safe way.
Take for example this very simple Employee class with a constructor:
You could do it like this:
public class Employee
{
private string _sex;
public Employee(string sex)
{
_sex = sex;
}
}
But now you are relying upon users to enter just the right value for that string.
Using enums, you can instead have:
public enum Sex
{
Male = 10,
Female = 20
}
public class Employee
{
private Sex _sex;
public Employee(Sex sex)
{
_sex = sex;
}
}
This suddenly allows consumers of the Employee class to use it much more easily:
Employee employee = new Employee("Male");
Becomes:
Employee employee = new Employee(Sex.Male);
Often you find you have something - data, a classification, whatever - which is best expressed as one of several discrete states which can be represented with integers. The classic example is months of the year. We would like the months of the year to be representable as both strings ("August 19, 2010") and as numbers ("8/19/2010"). Enum provides a concise way to assign names to a bunch of integers, so we can use simple loops through integers to move through months.
Enums are strongly typed constants. Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values, and with each possible value relating to a number, they can be used in a wide range of situations. As you will see in our example, enumerations are defined above classes, inside our namespace. This means we can use enumerations from all classes within the same namespace.
using System;
namespace ConsoleApplication1
{
public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
class Program
{
static void Main(string[] args)
{
Days day = Days.Monday;
Console.WriteLine((int)day);
Console.ReadLine();
}
}
}
Enumeration (Enum) is a variable type. We can find this variable type in C, C# and many other languages.
Basic Idea for Enum is that if we have a group of variable of integer type (by default) then instead of using too much int values just use a Enum. It is efficient way. Let suppose you want to write rainbow colours then you may write like this:
const int Red = 1;
const int Orange = 2;
const int Yellow = 3;
const int Green = 4;
const int Blue = 5;
const int Indigo = 6;
const int Violet = 7;
here you can see that too many int declarations. If you or your program by mistake change the value of any integer varialbe i.e. Violet = 115 instead of 7 then it will very hard to debug.
So, here comes Enum. You can define Enum for any group of variables type integers. For Enum you may write your code like this:
enum rainBowColors
{
red=1,
orange=2,
yellow=3,
green,
blue=8,
indigo=8,
violet=16)
};
rainBowColors is a type and only other variables of the same type can be assigned to this. In C#/C++ you need to type casting while in C you do not to type cast.
Now, if you want to declare a variable of type rainBowColors then in C
enum rainBowColors variableOne = red;
And in C# / C++ you can do this as:
rainBowColors variableOne = red;
There are two meanings of enumeration in C#.
An enumeration (noun) is a set of named values. Example:
public enum Result {
True,
False,
FileNotFound
}
Enumeration (noun form of the verb enumerate) is when you step through the items in a collection.
The IEnumerable<T> interface is used by classes that provide the ability to be enumerated. An array is a simple example of such a class. Another example is how LINQ uses it to return results as enumerable collections.
Edit:
If you want to compare a string to an enum value, you either have to parse the string to the enum type:
if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) ...
or convert the enum value to a string:
if (theString == Result.True.ToString()) ...
(Be careful how you compare the values, depending on whether you want a case sensetive match or not.)
If you want to enumerate a collection and look for a string, you can use the foreach command:
foreach (string s in theCollection) {
if (s == theString) {
// found
}
}
Another advantage of using Enum is that in case of any of the integer value needs to be changed, we need to change only Enum definition and we can avoid changing code all over the place.
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.
http://msdn.microsoft.com/en-us/library/cc138362.aspx
Enumeration (ENUM)
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
Lets Take an Example we are taking normal constant in a class like
int a=10;
by mistakely we assign new value to that variable in that same class like
a=20;
then we will get wrong data when we want access them.
enum provide secure way of accessing constant.
Also if we have many feild constant in a class we had to memorize them if we want to use them in a class.
but enum contains group of related name constant, if we want to access the constant then only we had to memorize enum name.
Enumerations in my experience have worked in very specific cases and should be used when you absolutely need to maintain this in your application. Problems come into play with Enums when you are working with multiple developers and some new developer comes on to a project and can adds a enum to the application no errors everything builds but then you have another full stack developer that maintains this same list in a lookup table in a different order. Kaboom!!!!
Burned way to many times with that one even if not intentional. Rule of thumb don't maintain a list of enums in a app over 5 or 6 items. If higher you might as well store them in a lookup table in the DB of your choice.
My app has a lot of different lookup values, these values don't ever change, e.g. US States. Rather than putting them into database tables, I'd like to use enums.
But, I do realize doing it this way involves having a few enums and a lot of casting from "int" and "string" to and from my enums.
Alternative, I see someone mentioned using a Dictionary<> as a lookup tables, but enum implementation seems to be cleaner.
So, I'd like to ask if keeping and passing around a lot of enums and casting them be a problem to performance or should I use the lookup tables approach, which performs better?
Edit: The casting is needed as ID to be stored in other database tables.
Casting from int to an enum is extremely cheap... it'll be faster than a dictionary lookup. Basically it's a no-op, just copying the bits into a location with a different notional type.
Parsing a string into an enum value will be somewhat slower.
I doubt that this is going to be a bottleneck for you however you do it though, to be honest... without knowing more about what you're doing, it's somewhat hard to recommendation beyond the normal "write the simplest, mode readable and maintainable code which will work, then check that it performs well enough."
You're not going to notice a big difference in performance between the two, but I'd still recommend using a Dictionary because it will give you a little more flexibility in the future.
For one thing, an Enum in C# can't automatically have a class associated with it like in Java, so if you want to associate additional information with a state (Full Name, Capital City, Postal abbreviation, etc.), creating a UnitedState class will make it easier to package all of that information into one collection.
Also, even though you think this value will never change, it's not perfectly immutable. You could conceivably have a new requirement to include Territories, for example. Or maybe you'll need to allow Canadian users to see the names of Canadian Provinces instead. If you treat this collection like any other collection of data (using a repository to retrieve values from it), you will later have the option to change your repository implementation to pull values from a different source (Database, Web Service, Session, etc.). Enums are much less versatile.
Edit
Regarding the performance argument: Keep in mind that you're not just casting an Enum to an int: you're also running ToString() on that enum, which adds considerable processing time. Consider the following test:
const int C = 10000;
int[] ids = new int[C];
string[] names = new string[C];
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i< C; i++)
{
var id = (i % 50) + 1;
names[i] = ((States)id).ToString();
}
sw.Stop();
Console.WriteLine("Enum: " + sw.Elapsed.TotalMilliseconds);
var namesById = Enum.GetValues(typeof(States)).Cast<States>()
.ToDictionary(s => (int) s, s => s.ToString());
sw.Restart();
for (int i = 0; i< C; i++)
{
var id = (i % 50) + 1;
names[i] = namesById[id];
}
sw.Stop();
Console.WriteLine("Dictionary: " + sw.Elapsed.TotalMilliseconds);
Results:
Enum: 26.4875
Dictionary: 0.7684
So if performance really is your primary concern, a Dictionary is definitely the way to go. However, we're talking about such fast times here that there are half a dozen other concerns I'd address before I would even care about the speed issue.
Enums in C# were not designed to provide mappings between values and strings. They were designed to provide strongly-typed constant values that you can pass around in code. The two main advantages of this are:
You have an extra compiler-checked clue to help you avoid passing arguments in the wrong order, etc.
Rather than putting "magical" number values (e.g. "42") in your code, you can say "States.Oklahoma", which renders your code more readable.
Unlike Java, C# does not automatically check cast values to ensure that they are valid (myState = (States)321), so you don't get any runtime data checks on inputs without doing them manually. If you don't have code that refers to the states explicitly ("States.Oklahoma"), then you don't get any value from #2 above. That leaves us with #1 as the only real reason to use enums. If this is a good enough reason for you, then I would suggest using enums instead of ints as your key values. Then, when you need a string or some other value related to the state, perform a Dictionary lookup.
Here's how I'd do it:
public enum StateKey{
AL = 1,AK,AS,AZ,AR,CA,CO,CT,DE,DC,FM,FL,GA,GU,
HI,ID,IL,IN,IA,KS,KY,LA,ME,MH,MD,MA,MI,MN,MS,
MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,MP,OH,OK,OR,PW,
PA,PR,RI,SC,SD,TN,TX,UT,VT,VI,VA,WA,WV,WI,WY,
}
public class State
{
public StateKey Key {get;set;}
public int IntKey {get {return (int)Key;}}
public string PostalAbbreviation {get;set;}
}
public interface IStateRepository
{
State GetByKey(StateKey key);
}
public class StateRepository : IStateRepository
{
private static Dictionary<StateKey, State> _statesByKey;
static StateRepository()
{
_statesByKey = Enum.GetValues(typeof(StateKey))
.Cast<StateKey>()
.ToDictionary(k => k, k => new State {Key = k, PostalAbbreviation = k.ToString()});
}
public State GetByKey(StateKey key)
{
return _statesByKey[key];
}
}
public class Foo
{
IStateRepository _repository;
// Dependency Injection makes this class unit-testable
public Foo(IStateRepository repository)
{
_repository = repository;
}
// If you haven't learned the wonders of DI, do this:
public Foo()
{
_repository = new StateRepository();
}
public void DoSomethingWithAState(StateKey key)
{
Console.WriteLine(_repository.GetByKey(key).PostalAbbreviation);
}
}
This way:
you get to pass around strongly-typed values that represent a state,
your lookup gets fail-fast behavior if it is given invalid input,
you can easily change where the actual state data resides in the future,
you can easily add state-related data to the State class in the future,
you can easily add new states, territories, districts, provinces, or whatever else in the future.
getting a name from an int is still about 15 times faster than when using Enum.ToString().
[grunt]
You could use TypeSafeEnum s
Here's a base class
Public MustInherit Class AbstractTypeSafeEnum
Private Shared ReadOnly syncroot As New Object
Private Shared masterValue As Integer = 0
Protected ReadOnly _name As String
Protected ReadOnly _value As Integer
Protected Sub New(ByVal name As String)
Me._name = name
SyncLock syncroot
masterValue += 1
Me._value = masterValue
End SyncLock
End Sub
Public ReadOnly Property value() As Integer
Get
Return _value
End Get
End Property
Public Overrides Function ToString() As String
Return _name
End Function
Public Shared Operator =(ByVal ats1 As AbstractTypeSafeEnum, ByVal ats2 As AbstractTypeSafeEnum) As Boolean
Return (ats1._value = ats2._value) And Type.Equals(ats1.GetType, ats2.GetType)
End Operator
Public Shared Operator <>(ByVal ats1 As AbstractTypeSafeEnum, ByVal ats2 As AbstractTypeSafeEnum) As Boolean
Return Not (ats1 = ats2)
End Operator
End Class
And here's an Enum :
Public NotInheritable Class EnumProcType
Inherits AbstractTypeSafeEnum
Public Shared ReadOnly CREATE As New EnumProcType("Création")
Public Shared ReadOnly MODIF As New EnumProcType("Modification")
Public Shared ReadOnly DELETE As New EnumProcType("Suppression")
Private Sub New(ByVal name As String)
MyBase.New(name)
End Sub
End Class
And it gets easier to add Internationalization.
Sorry about the fact that it's in VB and french though.
Cheers !
Alternatively you can use constants
If the question was "is casting enum faster than accessing a dictionary item?" then the other answers addressing the various aspects of the performance would make sense.
But here the question seems to be "is casting enum when I need to store their value to a database table going to negatively affect the application performance?".
If that is the case, I don't need to run any test to say that storing data in a database table is always going to be orders of magnitude slower than casting an enum or executing its ToString().
In this case I would say the important thing is readability and maintainability of the code. In simple cases enums will do the job cleanly, but I agree with other answers that dictionaries are more flexible in the long term.
Enums will greatly outperform almost anything, especially dictionary's. Enums only use single byte. But why would you be casting? Seems like you should be using the enums everywhere.
Avoid enum as you can: enums should be replaced by singletons deriving from a base class or implementing an interface.
The practice of using enum comes from an old style programming in C.
You start to use an enum for the US States, then you will need the number of inhabitants, the capitol..., and you will need a lot of big switches to get all of this infos.