What would I use an Enum for? - c#

I've declared an enum type,
assigned a variable to it
and now I am writing it to the console.
So what use does an enum type have in a real world application?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Enum
{
enum cars
{
Toyota, Nissan, Ferrari, Lamborghini
}
}
class Program
{
enum cars
{
Toyota, Nissan, Ferrari, Lamborghini
}
static void Main(string[] args)
{
int a = (int)cars.Ferrari;
Console.WriteLine(a);
}
}
}

Whenever a procedure accepts a limited set of variables, consider using an enumeration. Enumerations make for clearer and more readable code, particularly when meaningful names are used.
The benefits of using enumerations include:
Reduces errors caused by transposing or mistyping numbers.
Makes it easy to change values in the future.
Makes code easier to read, which means it is less likely that errors
will creep into it.
Ensures forward compatibility. With enumerations, your code is less
likely to fail if in the future someone changes the values
corresponding to the member names.
ref : MSDN

enum cars
{
Toyota, Nissan, Ferrari, Lamborghini
}
This isn't the best example, as there are way more types of car than that, and new car manufacturers pop up regularly, e.g. tiny custom shops.
What would I use an Enum for?
You'd use it for something that has more than once choice, but those choices are discrete, and aren't going to change (very often).
You'd use it in places that might otherwise require a string, but where you don't want to accept just any string.
Something like:
public enum DayOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
};
public void ScheduleRecurringAppointment(DayOfWeek day)
{
// Todo: Add appointment to DB here...
}
(note that this isn't an enum you should write yourself. There is one in the .Net framework already).
You can change enums, but it is painful, as you have to recompile all code that uses the enum.

You want to use enum values in your program to improve code clarity and make it easier to maintain. Enums provide better error-checking and compiler warnings. They store constants and important values. Check the Enums for a better clarification.
EDIT:
Enums can be used with IntelliSense in Visual Studio in real world
application.
They come in handy when you wish to be able to choose between a set
of constant values, and with each possible value relating to a
number, they can be used in a wide range of situations.
An enumeration type provides
an efficient way to define a set of named integral constants that may
be assigned to a variable.

One thing no-one has pointed out yet (unless I missed it) is the use of Enumeration Types to set bit flags. You can do bitwise operations (such as & and |) on enum values and also bitwise comparisons. This works with the FlagsAttribute attribute.
[Flags]
enum Days
{
None = 0x0,
Sunday = 0x1,
Monday = 0x2,
Tuesday = 0x4,
Wednesday = 0x8,
Thursday = 0x10,
Friday = 0x20,
Saturday = 0x40
}
class MyClass
{
Days meetingDays = Days.Tuesday | Days.Thursday;
}

This would probably be more useful:
public enum Transmission {
Manual,
Automatic,
SemiAutomatic
}
public class Car
{
public Transmission CarTransmission { get; set; }
}

Enum class contains many useful methods for working with enumerations. The beauty of enum is that your can process it as integer value and display as string.
You can find more in >> http://www.c-sharpcorner.com/uploadfile/puranindia/enums-in-C-Sharp/

You can variables of your enum type. They will only accept the values of the enum and that makes coding easier (I think)
For example:
Enum Cars { VW, Mercedes, Ford, Opel };
...
Cars myCar = Cars.VW;

Enums are for code readability, and can be used to restrict a type to a finite set of values.
A common use of Enums is for modelling of States in a business process - i.e. New States cannot be added on an adhoc basis, and would require further coding and testing.

The following are advantages of using an enum :
You clearly specify for client code which values are valid for the
variable.
In Visual Studio, IntelliSense lists the defined values.

Heres an example of using enums in asp.net to change the header texts of each column. I Used the enum to specify the index of which column in the gridview I want to alter.
private enum MENU_ITEM
{
Customer_ID = 0,
Customer_First_Name = 1,
Customer_Surname = 2,
Customer_DOB = 3,
Customer_Phone_Number = 4,
Customer_Email = 5,
Customer_Update = 6,
Customer_Delete = 7,
Customer_Transaction = 8
}
private void populateGridHeader()
{
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_ID].Visible = false;
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_First_Name].HeaderText = "First Name";
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_Surname].HeaderText = "Surname";
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_DOB].HeaderText = "Date of Birth";
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_Phone_Number].HeaderText = "Phone Number";
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_Email].HeaderText = "Email";
SearchCustomer_g.Columns[(int)MENU_ITEM.Customer_Transaction].HeaderText = "New Transaction";
}

Related

How does this work, where an Enum is set a value twice within the same declaration?

This enum is within some C# source code and has its value reset many times. How does it work, and why would someone do that?
internal enum RequestType : ushort
{
#region Asynchronous messages
Shutdown = 0,
BulkMessage,
#endregion
#region Synchronous message without response
P2PBarrier = 0,
Heartbeat,
ReportProxy,
LoadStorage,
SaveStorage,
ResetStorage,
#endregion
// This series repeats
}
As per the C# language specification (14.3 Enum members), there is nothing that keeps you from using duplicate enum values:
Multiple enum members may share the same associated value. The example
enum Color
{
Red,
Green,
Blue,
Max = Blue
}
shows an enum in which two enum members—Blue and Max—have the same
associated value.
As to how values are associated with enum constants when they're not explicitly defined, the spec (1.10 Enums) has the following to say (emphasis mine):
When an enum member declaration does not explicitly specify a value,
the member is given the value zero (if it is the first member in the
enum type) or the value of the textually preceding enum member plus
one.
So the enum in your question is equivalent to:
internal enum RequestType : ushort
{
#region Asynchronous messages
Shutdown = 0,
BulkMessage = 1,
#endregion
#region Synchronous message without response
P2PBarrier = 0,
Heartbeat = 1,
ReportProxy = 2,
LoadStorage = 3,
SaveStorage = 4,
ResetStorage = 5,
#endregion
}
As to why someone would use this approach, the only reason I can imagine (besides saving a couple of bytes) is that the same enum can be used in different contexts in an idiomatic way. For the given example, the author doesn't need to pollute the namespace with separate SyncRequestType and AsyncRequestType enums, but is still able to make idiomatic use of the constants in both contexts.
I will withhold my value judgement, but the obvious downside of this approach is that you lose compile-time checking and nothing prevents you from using constants that don't have any meaning in a given context (e.g. applied to your example, using a synchronous message type in an asynchronous context).

what is enum and where can we use it?

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
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 }
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.
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;
}
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

Smooth way to store enum to a DB

I have an enum like so.
public enum TimeFrame
{
Morning = 1,
Afternoon,
Evening
}
When an object containing a property of type TimeFrame is stored, there's a conversion using a switch statement making each value explicitly to 1, 2, and 3. The command string created is substituted from e.g. Evening to 3. The same when fetching from the DB - if there's a value of 1, it's being mapped manually and explicitly into Morning.
Is there a smooth way to storage the values of the enum "as is"? Or should we avoid doing so for a reason?
I've tried straight-off approach but that only gives the fall-back value all the way...
TimeFrame = row["TimeFrame"] as TimeFrame? ?? TimeFrame.Morning
You can cast enums to ints and vice versa, this is very fast. You can also convert between enums and strings, takes a bit more code, time, and storage. You can then trivially store ints or strings in your database.
If for some reason the O/R-mapper (or whatever technology you are using) cannot handle enum values, you can create an int property translating your enum:
// Do not map!
public TimeFrame TimeFrame { get; set; }
// Map!
public int TimeFrameInt {
get { return (int)TimeFrame; }
set { TimeFrame = (TimeFrame)value; }
}
The translation between ints and enums is simply done with casts; no switch statements required. This is possible and very fast, since enums are represented by ints under the hood.

Indexing a BitArray where bits are defined by a generic Enum

I'm working with pulling a stream of bytes off of a medical device, and have run into a really annoying data structure. Basically, I am getting back a 2-byte chunk where each bit represents a boolean value. This structure appears frequently enough in the byte stream to develop a struct/class around it, but in each instance, the bits mean completely different things.
So first I set up a bunch of Enums to represent all the different definitions the bit structure could have. (Note that not every bit is used in every definition. Sometimes there are breaks in between the important bits.)
EDIT: Removed all names that looked like 'flag.' I'm not using the [Flags] attribute, and this seems to be a point of contention/confusion. The enum values are simply mapped to the indices in my BitArray.
public enum RecordInfo { AM_TEST = 0, PM_TEST, TEST_VALIDITY };
public enum RecordAlerts { ALERT1 = 0, ALERT2, ALERT3, ALERT4, VALIDATED = 15 };
Then created this container to hold the actual bits:
public struct TwoBytes<TEnum> where TEnum : struct, IConvertible
{
private BitArray _bits = new BitArray(2);
}
This seems to work as I need, until I want to index my structure based on an Enum name. So say I have a TwoByte struct called Alerts, and this contains some bit values. If I want to get a specific flag like this:
bool alert3Set = Alerts[RecordAlerts.ALERT3]
I end up with a truly heinous index function. This is what I have in place now:
public bool this[TEnum name]
{
get
{
int index = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToList().Where(x => x.Equals(name)).Cast<int>().First();
return _bits[index];
}
}
Now it works, crazily enough. But that LINQ chains looks positively atrocious, and it takes a while to decipher what it's actually doing.
Is there a cleaner, more efficient way of converting a generic Enum 'name' to its integer value? Or would I be better suited to use a Dictionary (or some other object) to represent the bit structure definitions?
As long as every TEnum you'd use derives from int (the default), and not from another number type, this will work:
public bool this[TEnum name]
{
get
{
int index = (int)(object)name;
return _bits[index];
}
}
If you want to support enums derived from smaller types (and enums that only use values within the range supported by int), I'd use:
public bool this[TEnum name]
{
get
{
int index = Convert.ToInt32(name);
return _bits[index];
}
}
(fully supporting enums derived from types that can't implicitly be converted to int, like uint, long, and ulong, gets more complicated, because BitArray's indexer uses an int)
I think a bit of OOP would make your life easier. You can introduces classes that represent the data you receive, and has meaningful property names. Each class could accept your BitArray into constructor and parse it into properties.
Further in your program you could use these classes instead of fiddling with bits.
As FrankPI suggested in the comments, why not use an enum whose values really represent each bit, rather than using an intermediate BitArray?
[Flags]
public enum RecordFlags { FLAG1 = 0x1, FLAG2 = 0x2, FLAG3 = 0x4, FLAG4 = 0x8, FLAG5 = 0x10, VALIDATED = 0x8000 };
var readFlags = (RecordFlags) ((bytes[0] << 8) | bytes[1]);
bool hasFlag2 = (readFlags & RecordFlags.Flag2) != 0;

Enum vs Constants/Class with Static Members?

I have a set of codes that are particular to the application (one to one mapping of the code to its name), and I've been using enums in C# to represent them. I'm not sure now if that is even necessary. The values never change, and they are always going to be associated with those labels:
Workflow_Status_Complete = 1
Workflow_Status_Stalled = 2
Workflow_Status_Progress = 3
Workflow_Status_Complete = 4
Workflow_Status_Fail = 5
Should I use an enum or a class with static members?
Static members of type int seems to be inferior to an enum to me. You lose the typesafety of an enum. And when debugging you don't see the symbolic name but just a number.
On the other hand if an entry consists of more than just a name/integervalue pair a class can be a good idea. But then the fields should be of that class and not int. Something like:
class MyFakeEnum
{
public static readonly MyFakeEnum Value1=new MyFakeEnum(...);
}
Use an enum. Even though your codes never change, it will be difficult to know what the value represents just by inspection. One of the many strengths of using enums.
enum RealEnum : uint
{
SomeValue = 0xDEADBEEF,
}
static class FakeEnum
{
public const uint SomeValue = 0xDEADBEEF;
}
var x = RealEnum.SomeValue;
var y = FakeEnum.SomeValue;
// what's the value?
var xstr = x.ToString(); // SomeValue
var ystr = y.ToString(); // 3735928559
Not even the debugger will help you much here, especially if there are many different values.
Check out the State Pattern as this is a better design. With the idea you are using you'll end up with a large switch/if-else statement which can be very difficult to keep up.
I would lean towards enums as they provide more information and they make your codes "easier to use correctly and difficult to use incorrectly". (I think the quote is from The Pragmatic Programmer.

Categories

Resources