6

What is the difference between private variables in a clsClass type and using enumeration enum to instantiate the variable. This question arose when I was looking at some C# Class code for serial ports. example: private int SomeClassMember; and private enum TransmissionType{TEXT,HEX} ?

Where do the enum statements appear in a Class definition?

1
  • 2
    You may get more help on StackOverflow.com Jan 25, 2011 at 21:42

4 Answers 4

7

Adding to Eldritch Conundrum's answer (since he has not updated it):

In C#, enums can be declared in the same places as classes (which can be nested).

In many cases you might indeed be able to replace Enums
by simple constants or static classes with public constants, but there is more to Enums than meets the eye.

Intellisense (= auto completion in VS, MonoDevelop, etc...) provides support for enums, it does not do so for constants.

You should use enums to enforce strong typing on parameters, properties and return values that represent a set of values. The set of values should be closed, not subject to constant change.

You can extend enums:
Taken from: http://damieng.com/blog/2012/10/29/8-things-you-probably-didnt-know-about-csharp

public enum Duration { Day, Week, Month };

public static class DurationExtensions
{
    public static DateTime From(this Duration duration, DateTime dateTime) 
    {
        switch (duration)
        {
            case Duration.Day:
                return dateTime.AddDays(1);
            case Duration.Week:
                return dateTime.AddDays(7);
            case Duration.Month:
                return dateTime.AddMonths(1);
            default:
                throw new ArgumentOutOfRangeException("duration");
        }
    }
}

And of course Enums are usefull for Bitwise comparisons with the [Flags] attribute and in recent versions of .NET they have a .HasFlag method.

Not really an answer, just some extra info.

2
  • Could you do more than "adding to" Eldrich's answer - it makes it so that yours doesn't need to depend on someone else's and stands on its own. The sort order of the answers isn't the same for everyone.
    – user40980
    Feb 23, 2013 at 17:13
  • Yes, sorry about that. Updated it :-)
    – TimothyP
    Feb 24, 2013 at 14:54
4

I would first encourage you to read this small post by Microsoft.

In C#, enums cannot have a behaviour. If it helps, you can think of enums as members of a special class where instances just have names but no methods [this is strictly speaking not a correct visualization].

Class members however can have useful methods embedded into them.

Example,

public struct Color {
    public static readonly Blue = new Color (0, 0, 255);
    public static readonly Red  = new Color (255, 0, 0);
    //...etc.


    public int GetHue() {
        //Return the hue of the color
    }

    public int GetSimilarityCoefficient(Color another_) {
        //Some really ingenious algo to identify similarity of colors
    }
}

vs.

public enum Color {
    Blue,
    Red,
    Green
} //Cannot do anything much but use if-else/switch-case and make decisions in those blocks

This shows enums in a bad light and hence comes the question —when to use enums? And thus comes a highly personal, though I hope not widely rejected, answer.

I personally prefer to use enums when my members are supposed to only have token meanings (i.e., they are pure states) and when I want them to be extremely lightweight and when I want to ensure that all enumerations can be accounted for.

Example in a form that has several radio button choices (let's say to choose which type of copy to run),

public enum UserChoice {
    Copy,
    DeepCopy,
    PreviewOnly
}
…
//Somewhere
UserChoice userChoice = form.GetUserChoice();
switch (userChoice) {
    case UserChoice.Copy:
        //Run the copy algorithm
        break;
    case UserChoice.DeepCopy:
        //Run the deep copy algorithm
        break;
    //Forgot to handle PreviewOnly —> gives a compile exception
}

Note that I can accomplish the same using class variables too:

public class UserChoice {
    public static UserChoice Copy = new UserChoice();
    public static UserChoice DeepCopy = new UserChoice();
    public static UserChoice PreviewOnly = new UserChoice();
}
…
//Then somewhere 
UserChoice userChoice = form.GetUserChoice();
if (userChoice == UserChoice.Copy) {
    //Run the copy algorithm
}
else if (userChoice == UserChoice.DeepCopy) {
    //Run the deep copy algorithm
}
//Forgot to handle preview only. No compile exception.

Also, enums can be Flags.

[Flags]
public enum  UserChoice{
    Copy = 0,
    Deep = 1,
    Preview = 2,
    NoActualOp = 4
} //Thus, DeepCopy = Copy | Deep; DeepCopyWithPreview = Copy | Deep | Preview; CopyWithPreviewOnly = Copy | Preview | NoActualOp etc..
3
  • Great description, would just like to add that Enums can have behavior added to them using Extension methods, so adding GetHue() and GetSimilarityCoefficient() to an enum is possible.. it's just not used often
    – TimothyP
    Feb 24, 2013 at 14:56
  • 1
    @TimothyP Correct --but that involves casting etc. which defeats the purpose of OOO. Note that I can achieve GetHue() without extension methods too --e.g., by writing helper classes. But then my helper class/extension method becomes hardwired to the enum.
    – Apoorv
    Feb 27, 2013 at 11:47
  • Hah... did not think of it that way... makes sense, will have to remember that
    – TimothyP
    Feb 27, 2013 at 11:49
1

I'm going to take a wild guess and go with the idea that you've got something like this:

public class Foo
{
    private int Var1;
    private enum TransmissionType 
    {
         TEXT, HEX
    }

    public void DoesSomething()
    {
        if (somethingIsTrue)
            Var1 = HEX;
        else
            Var1 = TEXT;

        //more code.....
    }

}

In this case the enum is really being used as a substitute for declaring two constants like this

private const int TEXT = 0;
private const int HEX = 1;

The enum is just a private type similar in how you can have a private class within a public and/or internally scoped class. On the other hand Var1 above is a privately scoped instance of an integer (int). .NET (or at least C# anyhow) performs a conversion from an enum to an int automatically for you. This is fairly common when looking at a class that is a boundary between managed and unmanaged code. The managed code typically would have an enum that it would use to describe the value/meaning of the variable where older/unmanaged code typically would use constants.

1
  • 3
    In other words, enums are type safe names, where regular constants are just named arbitrary values.
    – Jeremy
    Jan 23, 2011 at 15:54
-2

In C#, enums can be declared in the same places as classes (which can be nested).

1
  • 2
    Hi Eldritch, welcome to Programmers.SE! Can you elaborate a little more on your answer?
    – user8
    Jan 25, 2011 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.