TomJ72

What do you really win by using enums compared to implementing a typesafe enum with a class or struct
(except from saving some inital time, since an enum is quicker to implement)
Can you get a significant (measurable/noticeable) performance gain with enums
Otherwise, what is the point of using them

I am asking this question, because I once started to use C# enums since I thought it was convenient to create an enum instead of creating a class. I used to do this for those types where I initially believed that there were not going to be any particular behaviour that should be grouped together with the type.
Later though, I have often ended up with if statements operating on these enums, and when I start needing to reuse those statements I wish I had created a class so that I could have put the method into the class instead of creating a non-object-oriented method in an external class which receive the enum as a parameter.

So, nowadays when I feel tempted to create an enum, I will instead create a struct with the typesafe enum pattern, to avoid future violations of object-oriented principles by not having the data and methods together within the type.

I just can not realize what I can loose by never using enums (except some inital coding time).
As an example, I can not understand why Microsoft, in the enterprise library, have created "RangeBoundaryType" as an enum instead of a struct.
What can the reason be to use an enum instead of a struct
(one disadvantage is less reusable code, but what can the advantage be )

For those of you who have not downloaded the enterprise library, here are some relevant parts of the code I am talking about:

Code Snippet

public enum RangeBoundaryType
{
/// <summary>
/// The range should include the boundary.
/// </summary>
Inclusive = 0,
/// <summary>
/// The range should exclude the boundary.
/// </summary>
Exclusive
}

public class AssertRangeAttribute : ValidationAttribute
{
...
private readonly RangeBoundaryType lowerBoundType;
...

protected override void ValidateCore(object instance, PropertyInfo propertyInfo, IList<ValidationError> errors)
{
...
IComparable compareToObject = (IComparable)propertyValue;
int lowerBoundGreaterThanValue = lowerBound.CompareTo(compareToObject);
...
if ((lowerBoundGreaterThanValue == 0) && (lowerBoundType == RangeBoundaryType.Exclusive)) addError = true;
if (lowerBoundGreaterThanValue > 0) addError = true;
...
}



Instead of using an enum "RangeBoundaryType" and the two if statements above, I would have preferred the RangeBoundaryType to have been a struct instead, so you for that struct could have created an "IsWithinInterval" (or whatever you would want to call it) method:

Code Snippet

if(!lowerBoundType.IsWithinInterval(compareToObject)) {
addError = true;
}



With this kind of code, one benefit is that the "IsWithinInterval" method encapsulates the comparisons (e.g. the lowerBound value and whether or not to include the boundary values, which could be done with either using subclasses/polymorphism or by using the if statements within the class), so that the method can be reused with the type, rather than duplicating the code whenever you want to use it.
Or another option (instead of duplication the comparisons) which I previously mentioned that I often have ended up with, would be to use an external (non-OO) class for the reusing purpose:

Code Snippet

class RangeBoundaryTypeUtility {
public static IsWithinInterval(IComparable compareToObject, RangeBoundaryType lowerBoundType)
{
....
}



However, using this kind of class and method, with if statements on an enum parameter ("RangeBoundaryType" in this case), is not something that is desirable in OO-code.

So, if some Enterprise Library developer is reading this:
Can you explain the advantage of having created "RangeBoundaryType" as an enum, and what disadvantage you would get if you would have created a struct instead


Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

IsshouFuuraibou

I think you're mistaken about what an enum is.

Enum (Enumeration) resources:
Enum (C#)
Enum Structure

Enumerations have their uses, and it is not as a light-weight class or structure.
Enums are part of the OO programming, just take a look at how many enums are used to describe attributes for forms and UI controls.

FormBorderStyle is a enum





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

Peter Ritchie

Enum are useful when you want to create a subset of "Types" for type safety. It's similar to implementing several derived classes from a base class. For example:

enum TriState

{

Unknown = 0,

On = 1,

Off = 2,

Both = 3,

};

void Method(TriState state) {/*...*/};

This would allow better type safety with calls to Method:

void Method(1); // CS1503

In order to get the same type safety (or better) without enum, you'd have to do something like:

public interface TriState
{
// ...
}

public struct On : TriState
{
// ...
}

public struct Off : TriState
{
// ...
}

public struct Both : TriState
{
// ...
}

I'm not clear where this question is coming from. Are you concerned that a enum member of a class is "data" and violates OO




Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

IsshouFuuraibou

Another advantage of enums, is the ability to convert from enum to it's base type with a cast and to use Enum.Parse to go from string names to enum values.

ie

TriState ConfiguredSwitch = (TriState)Enum.Parse( typeof(TriState), "Both" );

would give me a value of "Both" (3) for ConfiguredSwitch. Consider actually using a string from a configuration file, stream, or user input and you can see where this is very useful. Or if you are going from a selection where only the text matches, then you're not worried about having to work with converting index, you can just parse the text.





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

Peter Ritchie

IsshouFuuraibou wrote:
Another advantage of enums, is the ability to convert from enum to it's base type with a cast and to use Enum.Parse to go from string names to enum values.

ie

TriState ConfiguredSwitch = (TriState)Enum.Parse( typeof(TriState), "Both" );

would give me a value of "Both" (3) for ConfiguredSwitch. Consider actually using a string from a configuration file, stream, or user input and you can see where this is very useful. Or if you are going from a selection where only the text matches, then you're not worried about having to work with converting index, you can just parse the text.
Arguably, one might consider that a disadvantage as Enum.Parse returns and Object and therefore requires a cast. Not to mention the ability to cast any int to an enum despite being an invalid value:

public enum State
{
Unknown = 0,
On = 1,
Off = 2
}
State state = (State)99;






Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

OmegaMan

You have a lot of questions...and heck this may not answer any of them...

But If I had my druthers on the range boundary, I would have kept the enum but added the ranges as an attribute of the enum by creating a specialized attribute class.

Let me explain in pseudo code

Enum Decorated with Range Attribute
public enum RangeBoundaryType
{
[RangeAttribute(0, 100)] // This attribute can be on any enum!
Inclusive = 0,

[RangeAttribute(101, 200)]
Exclusive
}


Then on the RangeAttribute attribute class I would have a static to divine if it is within the range:

Attribute Class
public class RangeAttribute : Attribute
{

static bool WithinRange(object actualEnum, int userValue )
{
// Reflect upon the object (enum) and extract the ranges and compare
// the userValue to the range and reports if it is within or not.
// Or if it is not decorated, throw an exeception or return false.
}

}


Therefore the user can simply take any enum that is decorated with the attribute and determine if the item is within the range such as

Usage
int MyLower bounds = 102;

RangeAttribute.WithinRange ( RangeBoundaryType.Inclusive, MyLower ); // Returns false




Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

IsshouFuuraibou

Now you're just being argumentative...

But yes, it is a mixed blessing type of ability. It would be nice to have a typed parse for enum and some bounds checking/declarition for enums. However, being able to have a bitflag style of enum where Enabled and Shown are defined but Enabled | Shown is not defined but is still a valid enum value. Especially with FlagsAttribute set, then you'll get bitfield flagging

[FlagsAttribute]
public enum State
{
Enabled = 1,
Shown = 2
}

State s = State.Enabled | State.Shown;

State would have a value of 3, that isn't defined. However the enum would report it as Enabled, Shown instead of "3". Enum is more than just a list of constants. It is still good to know what enums can actually do.

Now that we've successfully turned the OP into a discussion over enums, which really does address the OP. Would you want to see Enum restricted to preset and derived values only, or would you want to leave it up to the programmer to understand that the specific value of enum is not required to be part of the defined set





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

Peter Ritchie

OmegaMan, how does declaring a new attribute for a enum make using enum easier You now can't use anything on the Enum class and are forced to use the RangeAttribute class to compare enum values. If RangeAttribute were built into C#, this would be useful.

It appears to me not mixing enums *and* a new class would be much easier, readable, and maintainable.






Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

OmegaMan

Peter Ritchie wrote:

OmegaMan, how does declaring a new attribute for a enum make using enum easier



The value add for me is when the need arises to Trojan Horse extra information onto an enum(s); which allows for specialized processing later. Usually this is done for error message enums where the code throws the enum due to a situation, and the response/report processor extracts the added textual information from the attributed enum and reports it back to the developer.

My thought in answering the post as I did was that the user mentions that he shy's away from the usage of enums ,due to what I perceived in his post, as a lack of flexibility of the enum.





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

IsshouFuuraibou

OmegaMan wrote:

My thought in answering the post as I did was that the user mentions that he shy's away from the usage of enums ,due to what I perceived in his post, as a lack of flexibility of the enum.


odd, I mostly focuesed on the statement from the original post:


I am asking this question, because I once started to use C# enums since I thought it was convenient to create an enum instead of creating a class. I used to do this for those types where I initially believed that there were not going to be any particular behaviour that should be grouped together with the type.
Later though, I have often ended up with if statements operating on these enums, and when I start needing to reuse those statements I wish I had created a class so that I could have put the method into the class instead of creating a non-object-oriented method in an external class which receive the enum as a parameter.


as the key point to the problem. I see the problem more as trying to use enum as a class/struct and vice versa. Or am I reading too much into what was posted Though I am pretty sure there isn't too many ways to read "to use C# enums since I thought it was convenient to create an enum instead of creating a class".

Enums are not method-less classes, they aren't even akin to classes. Their behavior is significantly different.





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

Rob Teixeira

Actually, Enums are in fact classes. They derive from Enum, which in turn derives from ValueType. The Enum values are read-only fields. The Enum class does in fact contain methods, although you cannot define custom methods for a custom enum subclass.





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

TomJ72

>TriState ConfiguredSwitch = (TriState)Enum.Parse( typeof(TriState), "Both" );
>would give me a value of "Both" (3) for ConfiguredSwitch. Consider actually
>using a string from a configuration file, stream, or user input
>and you can see where this is very useful.

Okay, then one other reason (or actually, this is essentially the same reason as I initially mentioned as "saving some inital time") for using enums is when you want to use some quick and dirty coupling between a config string (or even worse, a user input string) and the current variable name.
I say it is dirty, because there will be high coupling betwen the user input string and a variable name in the code.
For example, if you would rename the enum value TriState.Both to TriState.BOTH, then Visual Studio will take care of all static renaming, but it will never be able to automatically rename strings in the config file or be able to handle different spelling from user input.

A more clean way, for parsing a string into a concrete type (without a coupling to a current variable name) would be to use a factory class (with potentially different implementations of the factory parsers, for different input languages), so that for example the english users could have their input strings "BoTh" or "bOtH" mapped to either TriState.Both or TriState.BOTH depending on the current variable name in the TriState type.

If you use a factory/parser class, there would be no need for using an enum but you could also let the factory parser create a class or struct.
In other words, if you want to parse config/input strings the clean way, then there seem to be no advantage of using a enum instead of a struct, but if you want do it in a convenient quick way, yes then the development time can indeed be an advantage.




Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

TomJ72

IsshouFuuraibou wrote:
I think you're mistaken about what an enum is.

Enum (Enumeration) resources:
Enum (C#)
Enum Structure

Enumerations have their uses, and it is not as a light-weight class or structure.
Enums are part of the OO programming, just take a look at how many enums are used to describe attributes for forms and UI controls.

FormBorderStyle is a enum


IsshouFuuraibou
>Enums are part of the OO programming, just take a look at how many enums are used to describe attributes for forms and UI controls.

Well, I am not convinced that is the truth if you mean the C# enum can be considered as pure OO programming, but if you mean that enums are part of OO in the sense that C# enums are frequently used by a lot of people (including MS developers) and that C# is considered as a language having quite good support for OO programming, then I agree.

If we were talking about Java enums, I would agree that Java enum is a real OO abstract data type since you can put methods into the enum, like this:

Java enum:

public enum TriState {
Unknown, On, Off, Both;

public TriState Toggle() {
if (this.equals(On)) {
return Off;
} else if (this.equals(Off)) {
return On;
} else {
return Unknown;
}
}
}

In C# enums, where it is not an OO abstract data type, the non-oo solution for an Toggle operation must be to externalize it, i.e. put it outside of the class:
public enum TriState
{
Unknown, On, Off, Both
};

public class TriStateUtility
{
public static TriState Toggle(TriState triState)
{
if (triState.Equals(TriState.On))
{
return TriState.Off;
}
else if (triState.Equals(TriState.Off))
{
return TriState.On;
}
else
{
return TriState.Unknown;
}
}
}


The OO solution in C# could be to use a struct instead:

public struct TriState
{
public static TriState Unknown = new TriState(0);
public static TriState On = new TriState(1);
public static TriState Off = new TriState(2);
public static TriState Both = new TriState(3);

private int value;
private TriState(int value)
{
this.value = value;
}

public TriState Toggle()
{
if (this.Equals(On))
{
return Off;
}
else if (this.Equals(Off))
{
return On;
}
else
{
return Unknown;
}
}

public override bool Equals(object obj)
{
if (!(obj is TriState))
{
return false;
}
TriState tristate = (TriState)obj;
return this.value.Equals(tristate.value);
}

public override int GetHashCode()
{
return value.GetHashCode();
}
}

However, there is indeed a lot of overhead for doing the above struct, so a reason to actually use enums instead,
is quicker development time. Or is there actually another benefit to use the non-OO programming style (i.e. C# enums).

Can someone provide an example of a really good reason to create an enum instead of creating struct, except from the
reason of quicker development time with enums compared to implementing your own typesafe structs with private constructors and instances defined with public static instances (as illustrated in the last code example above)


Regarding the Toggle method I added above, some of you now may have the following kind of feeling:
"Okay, if I knew that there would be a need for a toggle feature, then I agree that a struct/class would be better than an enum".
To those of you who have that feeling, but still will feel a desire to continue using enum, I would like to ask: Why
Is it because you actually are sure that you have the full understanding of your application from the beginning (when you start implementing your enum) and that you are able to predict whether there will be any future methods that would belong within the enum (if it would be possible with C# as it is in Java)
If you are not sure about the future need of methods within the type, but simply believe that you will not need any methods, why take the chance, i.e. why not create a typesafe struct instead to make it possible to insert methods into the type
Is it because you think it will be little overhead to refactor in the future when you discover methods you would like to put into the type, i.e. you think it is easy to refactor an enum to a struct in the future when you want to put methods into it, and it is not worth the effort to initially create a struct until you are sure you need it
In other words, is your reason for initially using enums (until you realize you need a class/struct with methods) just a way of applying agile/XP and intially writing as little code as possible
Or do you have any other good purpose for why enum is a better choice than a struct or class
(the question goes to those who really believe they are good OO developers, and not to those who think procedural programming is just as good and do not mind to use C# static methods just about everywhere without any OO abstractions at all)



>Enums are not method-less classes, they aren't even akin to classes. Their behavior is significantly different.

Well, in C# they do not even let you put any behaviour (methods), so indeed they are very different.
In Java, the enums can have methods, so there they are not at all significantly different.
Though, in this forum the topic is .NET and the fact that the C# non-OO enums do exist does not explain why you would want to use
a non-OO type, unless you prefer procedural programming in a language that supports real OO abstract data types (class/structs to which you can add methods that operates on the data in the type).




Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

TomJ72

Peter Ritchie wrote:

Enum are useful when you want to create a subset of "Types" for type safety. It's similar to implementing several derived classes from a base class. For example:

enum TriState

{

Unknown = 0,

On = 1,

Off = 2,

Both = 3,

};

void Method(TriState state) {/*...*/};

This would allow better type safety with calls to Method:

void Method(1); // CS1503

In order to get the same type safety (or better) without enum, you'd have to do something like:

public interface TriState
{
// ...
}

public struct On : TriState
{
// ...
}

public struct Off : TriState
{
// ...
}

public struct Both : TriState
{
// ...
}

I'm not clear where this question is coming from. Are you concerned that a enum member of a class is "data" and violates OO



> Are you concerned that a enum member of a class is "data" and violates OO

No, the type itself should be an abstraction of something, and in OO a class should be used as the abstraction so that you can put methods in that class which will use the data, rather than using an external class frequently pulling out data from it.
I consider this as a fundemental OO concept, which is described in the GRASP pattern "Information Expert" ("Applying UML and patterns", Craig Larman) like this:
"Assign a reponsiblity to the information expert - the class that has the information necessary to fulfil the responsibility"

For example, if you want to have a Toggle operation for the TriState enum (in C#), you would have to do something like this, i.e. you have to put the operation outside of the type:

public class TriStateUtility
{
public static TriState Toggle(TriState triState)
{
if (triState.Equals(TriState.On))
{
return TriState.Off;
}

Conceptually, the above kind of code is very similar to the following kind of procedural programming code (if TriState would be a class).

public class TriStateClassUtility
{
public static TriStateClass Toggle(TriStateClass triState)
{
if (triState.GetCurrentState().Equals(TriStateClass.On.GetCurrentState()))
{
return TriStateClass.Off;
}

From a conceptual design perspective, the above code snippets, with a procedural programming style, are very similar by its nature, even though from a technical/syntactical perspective, the enum code is shorter, since the state is encapsulated within the enum itself, so you do not need to invoke any getters.

In real OO, the toggle method should instead be defined in the class itself:

public class TriStateClass
{
// ...
public static TriState On = new TriState(1);
public static TriState Off = new TriState(2);
// ...
public TriStateClass Toggle()
{
if (this.GetCurrentState().Equals(On.GetCurrentState()))
{
return Off;
}


>In order to get the same type safety (or better) without enum,
>
you'd have to do something like:
> public interface TriState...

No, I would rather use something like this:
public struct TriState
{
public static TriState Unknown = new TriState(0);
public static TriState On = new TriState(1);
public static TriState Off = new TriState(2);
public static TriState Both = new TriState(3);

private int value;
private TriState(int value)
{
this.value = value;
}
....

For a more complete code sample, see another posting of mine in this thread.





Re: Visual C# Language Why using "method-less" enums in a OO language such as C# ?

TomJ72

Rob Teixeira wrote:
Actually, Enums are in fact classes. They derive from Enum, which in turn derives from ValueType. The Enum values are read-only fields. The Enum class does in fact contain methods, although you cannot define custom methods for a custom enum subclass.


Yes, okay there are classes, but there is a big limitation to C# enums when you can not put your own methods into them, as you can with Java enums.
In other words, I would like to say that Java enums are real OO abstract data types, while C# enums are not, but they are instead encouraging a procedural programming style, even though they exist in a language that can support OO programming.