Enum VS Static Class (Normal and With String Values)

27,515

Solution 1

From Enumeration Types (C# Programming Guide):

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 following are advantages of using an enum instead of a numeric type:

  1. You clearly specify for client code which values are valid for the variable.

  2. In Visual Studio, IntelliSense lists the defined values.

So if you pass enum, it is strongly typed, so you automatically get control over what you can pass into a method.

ScreenSizeEnum size = ScreenSizeEnum.Medium;
SetScreenSize(size); 

When using const or static fields you definetely need to check whether the passed int value is taken from the expected diapason.

int somevalue = ...;//anything
SetScreenSize(somevalue); //compiles

private void SetScreenSize(int Screen)
{
    switch (Screen)
    {
        case ScreenSizeClass.Large:
            //Do Logic
            break;
        case ScreenSizeClass.Small:
            //Do Logic
            break;
        default: 
            // something else, what to do??
            break;
    }
}

Based on comments:

If it's necessary to check, whether some int is defined in enum, one can do something like this:

int somevallue = 0;
if(Enum.IsDefined(typeof(ScreenSizeEnum), somevallue))
{
    //it's ok
}

Or an extension method:

public static T GetEnumValue<T>(this string value) where T : struct
{
    Type t = typeof(T);
    if (!t.IsEnum)
        throw new Exception("T must be an enum");
    else
    {
        T result;
        if (Enum.TryParse<T>(value, out result))
            return result;
        else
            return default(T);
    }
}

which could be used

int somevalue = 1;
ScreenSizeEnum size = somevalue.GetEnumValue<ScreenSizeEnum>();

As for the string (based on OP's edited question):

From enum (C# Reference):

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

So you cannot have an enum of strings. But you can use names from enums, as ToString method returns the name, not the value of the enum.

ScreenSizeEnum.Small.ToString(); //Small

So you can have another extension method on strings:

public static T GetEnumValue<T>(this string value) where T : struct
{
    Type t = typeof(T);
    if (!t.IsEnum)
        throw new Exception("T must be an enum");
    else
    {
        if (Enum.IsDefined(t, value))
            return (T)Enum.Parse(t, value);
        else
            return default(T);
    }
}

So that

int i = (int)ScreenSizeEnum.Small;
string str = ScreenSizeEnum.Small.ToString();
ScreenSizeEnum isize = i.GetEnumValue<ScreenSizeEnum>();//ScreenSizeEnum.Small
ScreenSizeEnum strsize = str.GetEnumValue<ScreenSizeEnum>();//ScreenSizeEnum.Small

Solution 2

This is precisely what enums are there for. Not that you can't use the static class with the constants, but enum is by far cleaner...

Solution 3

enums are basically used when you want a variable or parameter to have value from a fixed set of possible constants. You can replace enums with class with a set of static final int constants. But using enums is more flexible & readable appraoch over the later one.

Share:
27,515
Akhil Sekharan
Author by

Akhil Sekharan

When love &amp; skill works together, expect a masterpiece

Updated on September 18, 2020

Comments

  • Akhil Sekharan
    Akhil Sekharan over 3 years

    I have been developing for windows mobile and android for sometime. And I'm confused about these two concepts.

    Let's say I want to make decision based on some the user's device Screen Size. So I'll expect so predefined values. I could use a switch statement for handling my logic. But I'm not sure whether I should use Enum of a Static Class for this purpose. Which one is a better approach. I can do my logic in these two different ways. Which one is the correct approach? I'm confused. And is it possible for me to use String values also? Because currently I'm sticking with classes, I need to update to use all enums. So How about changing my Class to String Enum? Any way. Thanks.

    Using Enum

    //My predefined values
    public enum ScreenSizeEnum
    {
        Small, Medium, Large, XLarge,
    }
    //Handling Logic
    private void SetScreenSize(ScreenSizeEnum Screen)
    {
        switch (Screen)
        {
            case ScreenSizeEnum.Large:
                //Do Logic
                break;
            case ScreenSizeEnum.Small:
                //Do Logic
                break;
        }
    }
    

    Using Class

    //My predefined values
    public class ScreenSizeClass
    {
        public const int Small = 0;
        public const int Medium = 1;
        public const int Large = 2;
        public const int XLarge = 3;
    }
    //Handling Logic
    private void SetScreenSize(int Screen)
    {
        switch (Screen)
        {
            case ScreenSizeClass.Large:
                //Do Logic
                break;
            case ScreenSizeClass.Small:
                //Do Logic
                break;
        }
    }
    
  • PRouleau
    PRouleau over 11 years
    That's right. The users of SetScreenSize() clearly known they have to pass specific values and not an int who may be the screen width like 640.
  • Mike Zboray
    Mike Zboray over 11 years
    You can always cast an arbitrary int to an enum so you should still check enums for validity too.
  • Squonk
    Squonk over 11 years
    Except don't attempt to use enums in Java the way the OP has demonstrated in their question.
  • horgh
    horgh over 11 years
    @mikez That is another question and besides there is nice bunch of methods for that.