0

Why should I use an enum when I don't know to why even use it, I searched on other websites and they did 2 things, either explain 'What' an enum is and not why to use it, or the other which was just about how an enum is useless. So I did

public enum days  
{             
    Monday,   
    Tuesday,  
    Wednesday,
    Thursday, 
    Friday,   
    Saturday, 
    Sunday    
}             

and then

Console.WriteLine(days.Wednesday); 
Console.ReadKey();                 

However, instead of doing days.Wednesday why don't I just type

Console.WriteLine("Wednesday");
Console.ReadKey(); 
LarsTech
  • 80,625
  • 14
  • 153
  • 225
AztecWest
  • 11
  • 4
  • `"Wednesday"` is *completely* different from an enum containing labeled values, one of which is `Wednesday`. If you mistype the name in a string, you won't get a compilation error. If you do the same with an enum, Intellisense will complain immediately and if you try to compile, the compiler will throw a clear error. – Panagiotis Kanavos Jul 07 '20 at 17:03
  • Yes, enums have limitations, but until we get F#-style discriminated unions, they are the best way to specify a set of pre-defined values – Panagiotis Kanavos Jul 07 '20 at 17:05
  • Another *very* important difference is that you can't implement bit flags with strings. – Panagiotis Kanavos Jul 07 '20 at 17:05
  • I'd be curious for the arguments of why an enum is useless... – Austin T French Jul 07 '20 at 17:07
  • 1
    `Why should I use an X when I don't know to why even use it` - the same can be said about any abstraction or concept if you don't understand it. – ColinM Jul 07 '20 at 17:07
  • We could also encourage OP to [search](https://stackoverflow.com/a/3519460/3791245) [StackOverflow](https://stackoverflow.com/a/8076896/3791245) for [similar](https://stackoverflow.com/a/4709224/3791245) [questions/answers](https://stackoverflow.com/q/38468017/3791245) before asking the question. – Sean Skelly Jul 07 '20 at 17:27
  • Does this answer your question? [What is main use of Enumeration?](https://stackoverflow.com/questions/3519429/what-is-main-use-of-enumeration) – Pavel Anikhouski Jul 07 '20 at 18:11

4 Answers4

4

The purpose of using enums is to create a data type which will be represented as set of constant values like days of the week, months etc. also enums make Your code easier to read. An example of enums in C# is public enum Keys, if You want to check which key has been pressed by user it is easier to understand when You check it this way:

if (key == Keys.A)
{
    //do something
}

instead of:

if (key == 65)
{
    //do something
}

When I read the first code I immediately understand what it does, for the second one I would have to check which key has a value of 65.

Grobocop12
  • 154
  • 6
  • 1
    Thank you for the explanation, it was short and simple and just very easy to understand also this is my first question asked in Stack Overflow and seeming that people such as you can be very helpful I will use it more :) – AztecWest Jul 13 '20 at 16:57
1

There are plenty of reasons to use an Enum. Specifically over a "magic string" like you illustrated.

It might seem like more overhead for the developer to use an Enum, but it pays dividends.

 if(userSelectedDay == "Wedneday")

Looks fine until the user's culture changes for example:

var culture = new System.Globalization.CultureInfo("ja-JP");
var day = culture.DateTimeFormat.GetDayName(DateTime.Today.DayOfWeek);

Which your code will now be dealing with (internally):

if("火曜日" == "Wednesday")

Whereas using the Enum, you can respect that internally Wednesday in any language is an Integer. Specifically it's 3.

In a database this can have significant advantages well: Saving an integer instead of a string can mean:

  1. varchar(x) isn't a worry, is 255 characters too long for a date? Or should it be nvarchar(50)?
  2. Normalized Data: That one time code let's "wednesday" in, instead of "Wednesday" your data isn't broken
  3. Ints are smaller
  4. Querying for schedules.Where(w => w.DayOfWeek == (int)Today.DayOfWeek).ToList() is cheaper and easier to maintain.

These are quick and off the cuff, not an all inclusive list.

Austin T French
  • 5,022
  • 1
  • 22
  • 40
1

C# is a mostly statically-typed language, which has all the advantages and disadvantages associated with static typing. For a comparison / explanation of static and dynamic typing, see this question. But what it essentially boils down to is that static typing allows you to specify restrictions on values that can be checked during compilation, instead of runtime.

In light of that, the main reason to use enums would be to ensure that certain variables, parameters, etc., conform to a subset of values. For instance, if I declare a method like this:

public decimal GetRequiredWorkHours(days dayOfWeek)

Then it's clear that the method must be passed a day of the week, not any other kind of value. Thus, the following is a valid call:

var myHoursForFriday = GetRequiredWorkHours(days.Friday);

But the following examples are not:

... = GetRequiredWorkHours("Friday");
... = GetRequiredWorkHours("Bob");
... = GetRequiredWorkHours(new DateTime(2020, 07, 07));

The advantage is that these invalid calls are detected at compile time. In other words, I can't make a valid C# program that has one of these calls in it.

Had we instead declared the parameter as a string...

public decimal GetRequiredWorkHours(string dayOfWeek)

...then the compiler would accept all of these:

... = GetRequiredWorkHours("Friday");
... = GetRequiredWorkHours("Frday");  // misspelling
... = GetRequiredWorkHours("Bob");    // not a valid day
... = GetRequiredWorkHours(null);     // string is a reference type, unlike enums, so null is permitted

...even though only the first one is valid. The compiler has no idea what strings are valid, just that the method takes a string. So you will have to code it yourself inside the method to check for which strings are valid, and that check will occur at runtime. This allows for bugs to be introduced that aren't present when using a stronger-typed parameter.

In your example, calling Console.WriteLine(object) with an enum has the advantage that you can't, for example, mis-type the day name. However, since the parameter is of type object, and the method converts the object to a string via ToString(), this type information is lost inside the WriteLine method - which is OK, because the WriteLine method just needs to know how to represent the value in text, it doesn't have to know anything about what the value actually means.

This logic applies to more than parameters. For instance, you can have variables that are strongly-typed to a day of the week, etc. And your IDE will allow you to rename enum elements much more easily than if you had used string constants.


Now, having said all that, enums are actually not the greatest example of strong typing in C#. That's because they are really just aliases for int values (or another integer type if you specify it as such). Normally the integer for each enum value is implicit, but you can specify it explicitly, and some style guides suggest you do so. E.g.:

public enum days  
{             
    Monday = 0,   
    Tuesday = 1,  
    Wednesday = 2,
    Thursday = 3, 
    Friday = 4,   
    Saturday = 5, 
    Sunday = 6    
}   

This has some advantages - for instance, you can represent bit flags by specifying powers of 2 as the numbers. However, it also has some disadvantages, most importantly, that it's not just the specified enum values which are valid for a variable / expression of that type. Any integer can be put into that value, e.g.:

... = GetRequiredWorkHours((days) 17);
... = GetRequiredWorkHours((days) -1);
... = GetRequiredWorkHours(0);

There's also the issue that a new value could be introduced to the enum after a method that is used for it is written. While extremely unlikely in your example (I suspect the number and name of days in the week will not change in our lifetimes), other cases may frequently be updated.

To account for either of these scenarios, the method will have to double-check that the value passed to it is actually one it recognizes, e.g.:

public decimal GetRequiredWorkHours(days day)
{
    switch (day)
    {
        case days.Monday:
        case days.Tuesday:
        case days.Wednesday:
        case days.Thursday:
        case days.Friday:
            return 40;
        case days.Saturday:
        case days.Sunday;
            return 0;
        default:
            throw new Exception("Unrecognized day");
    }
}

While a day of the week is a good fit for an enum, other values may be better served by creating classes and/or subclasses. This allows the value to carry information in addition to its identity.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34
0

Conceptually, enums are certainly simpler than arrays and lists. Enums allow a developer to create a value type consisting of a set of named constants.

In normal human language, enums let you create “categories” of things and place them into their own type. An example will help to drive the point home.

Let’s say you have a payroll system which keeps track of employee types. These types include values like:

  • contractor
  • salaried
  • hourly
public enum EmployeeType {
  Salaried,
  Contractor,
  Hourly
}

The compiler assigns an integer to each category when the code is compiled. In the above example, “Salaried” will be assigned zero, “Contractor” will be assigned the number one, and so on.

This makes storage of enums very simple. In fact, they’re value types, meaning that they’re stored on stack memory, not heap memory.

The benefit comes in the form of code readability and reliability. Continuing with the payroll system example, if you have payroll numbers assigned to each type of employee, you no longer need to compare an employee type to a number explicitly, like this:

if(employee.employeeType == 2) {
  // some code...
}
hasib_ullah
  • 180
  • 1
  • 15