what is enum and where can we use it?

2020-04-07 18:53发布

While I code every time I used List<T>, string, bool etc. I did't see anywhere a use of an enum. I have an idea that enum is a constant but in practice, where do we actually use it. If at all we can just use a

public const int x=10; 

Where do we actually use it?

Kindly help me

标签: c#
4条回答
家丑人穷心不美
2楼-- · 2020-04-07 19:06

A constant lets us define a name for a value in one place in our code.

An enum is like defining a set of constants and lets us declare variables, properties, and parameters that can only use one of those constants.

For example, suppose we have a SalesOrder class for orders we receive on a website, and each SalesOrder can have a status - perhaps New, Shipped, Canceled, etc.

We could do it like this:

public class SalesOrder
{
    public string OrderStatus {get;set;}

But then someone could set that property to something completely invalid, like

order.OrderStatus = "Hello!";

We could decide that we'll give each status a number instead to prevent someone using some crazy value. So we change it to

public class SalesOrder
{
    public int OrderStatusCode {get;set;}

and we decide that 1 = New, 2 = Shipped, 3 = Canceled, etc. But that still doesn't fix anything, because someone can set OrderStatusCode = -666 and we're still messed up.

In any one of these cases we could improve on this with constants, like

const string SHIPPED_ORDER_STATUS = "Shipped";

or

const int NEW_ORDER_STATUS_CODE = 1;

But that still doesn't really solve the problem. It helps us to do this:

order.OrderStatusCode = NEW_ORDER_STATUS_CODE;

and that's good. But it still doesn't prevent this:

order.OrderStatusCode = 555; //No such order status code!

An enum lets us do this:

public enum OrderStatuses
{
    New,
    Shipped,
    Canceled
}

public class SalesOrder
{
    public OrderStatuses OrderStatus {get;set;}

Now it's impossible to set OrderStatus to any invalid value. It can only be one of the values in OrderStatuses.

Comparisons become a lot easier too. Instead of

if(string.Equals(order.OrderStatus,"shipped",Ordinal.IgnoreCase))

or

if(order.OrderStatusCode == 3) //What does three mean? Magic number!

We can do

if(order.OrderStatus == OrderStatuses.Shipped)

Now it's readable and easier to maintain. The compiler will prevent using any invalid value. If you decide you want to change the name of a value in OrderStatuses you can just right-click and rename it. You can't do that with a string or an int.

So an enum is very useful in that scenario - if we want to have a type with a limited, predefined set of values.


The most common use for constants is if we're putting a string or a number in our code that either repeats or has no apparent meaning, like

if(myString.Length > 434) //What is 434? Why do I care if it's more than 434?

We might declare a constant like

const int MAX_FIELD_LENGTH = 434;

Now this makes sense:

if(myString.Length > MAX_FIELD_LENGTH) //Now it's obvious what this check is for.

It's a small detail but it signals our intent and keeps us from storing a value in multiple places.

查看更多
戒情不戒烟
3楼-- · 2020-04-07 19:15

An enum is a convenient way to use names instead of numbers, in order to denote something. It makes your code far more readable and maintainable than using numbers. For instance, let that we say that 1 is red and 2 is green. What is more readable the following:

if(color == 1)
{
    Console.WriteLine("Red");
}
if(color == 2)
{
    Console.WriteLine("Green");
}

or this:

enum Color { Red, Green}

if(color == Color.Red)
{
    Console.WriteLine("Red");
}
if(color == Color.Green)
{
    Console.WriteLine("Green");
}

Furthermore, let that you make the above checks in twenty places in your code base and that you have to change the value of Red from 1 to 3 and of Green from 2 to 5 for some reason. If you had followed the first approach, then you would have to change 1 to 3 and 2 to 5 in twenty places ! While if you had followed the second approach the following would have been sufficient:

enum Color { Red = 3 , Green = 5 }
查看更多
成全新的幸福
4楼-- · 2020-04-07 19:17

Suppose you need to flag users in a software with roles, then you can declare an enum to define these roles, for sample:

public enum UserRole
{
   Master = 1,

   Developer = 2,

   Tester = 3,

   Manager = 4
}

Then, you can use this type UserRole in your User entity. It work as an integer value but it is more legible than an integer.

You could implement something like this:

if (user.Role == UserRole.Master) {
   // some action for master
} else if (user.Role == UserRole.Developer) {
   // another action for developer
}

or

switch (user.Role)
{
   case UserRole.Master:
      // some action for master
      break;
   case UserRole.Developer:
      // some action for developer
      break;
   case UserRole.Tester:
      // some action for tester
      break;
   case UserRole.Manager:
      // some action for manager
      break;
}
查看更多
Lonely孤独者°
5楼-- · 2020-04-07 19:21

Just adding a little bit more on enums: Enumerators are named constants. If you are using a set of named constants in your application you can go with enums instead of hard coding those constants. Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. But you can change the default type.

 enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. You can change the first value

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

The sequence of elements is forced to start from 1 instead of 0.

You can change the default type of enum, But must be any integer type.

enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Practical Scenario You can create a enum of status of your project Task

public enum Status
        {
            started,
            completed,
            notstarted
        }  

And you can use the enum like

Status.started
查看更多
登录 后发表回答