What is enum?
The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined. An enum is a value type and are created on the stack and not on the heap (dynamic memory).
The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. Enum may byte, sbyte, short, ushort, int, uint, long, or ulong type etc. There must be a numeric value for each enum type. The beauty of enum is that your can process it as integer value and display as string.
Following are some of advantages of using Enum and also given some of the points to remember while handling Enum. Enum always makes life easier for developer and also helps the stranger while reading code.
Advantage of using Enum
Enums are not allocated in memory. They exist only on compilation stage. When code runs - there is no enums there anymore.
If you writing the Architectural Code, then You have to go for Enum not Const variable String like 'const sting Player="Afridi"
Enum.Parse(), this is very useful, if you consider the web application if the query string "player=afridi" in the URL, then we use to Get Enum and use throughout the Application, it is helpful.
Main thing is Readability, you should always remember this.
Enum.Parse throws error if value is incorrect, so we use Enum.IsDefined to check. So every helper method in Enum helps a lot.
If you have choice like list of action or options or possibilities, then you can go for Enum. eg. Users (admin, salesperson, customer etc.).
You will get error in compile time itself not run time, it is better and best practice.
As you know it is a value type and also we can customize the Enum value.
It reduces the chance of bugs in code something like case sensitive problem.
IntelliSense makes you happy to work as you know how much it is helpful while programming. This is also the best use of Enum. Once place we use Admin, in other place we use admin, it is inconsistent too. If you think of it, it helps a lot. You don't have to remember the string fully , just type Enum and Make a dot it shows the list.
Summary
List of action or options or possibilities then we can use then best practice is always enum.
Enum in action (Explain through code in C# Console Applicaion)
using System;
namespace enum_example
{
class Program
{
public enum PlayerOfPakTeam : byte //Explicitly define PlayerOfPakTeam Enum as byte
(bydefault enum is int type.)
{
Hafeez = 1, //Explicitly started our enum form 1 (default starts from
0)
Shehzad = 2,
Malik = 3,
Umer = 4,
Maqsood = 5,
Babar = 6,
Afridi = 7,
Surfaraz = 8,
Sohail = 9,
Wahab = 10,
Amir = 11,
}
static void Main(string[] args)
{
string[] playerArray = Enum.GetNames(typeof(PlayerOfPakTeam));
foreach (string player in playerArray)
{
Console.WriteLine(player);
} Console.WriteLine();
}
}
(Practice Makes a Man Perfect)
(Practice Makes a Man Perfect)
No comments:
Post a Comment