C enums LEARNOVITA

C# Enumerations Type Tutorial | Learn Everything about Enum

Last updated on 12th Aug 2022, Blog, Tutorials

About author

Manish Kiran (C# Developer )

Manish Kiran is a C# Developer expert and subject specialist who have experience with Git, WPF, WinForms, C#,.Net, SQL, .NET Development, VB, .NET Framework,.NET Core, SVN, Mercurial. His articles help the learners to get insights about the Domain.

(5.0) | 19471 Ratings 2035

C# – Enums Introduction :

A specification may be a bunch of named range constants. A listed kind is proclaimed utilizing the enum slogan. C# lists area unit esteem info kind. All in all, identification contains its own qualities and can’t acquire or pass on gifts. saying enum Variable in C# – Enums Introduction The overall linguistic structure for saying a listing a listing enum ; Where The enum_name determines the identification kind name. The count list may be a comma-isolated summation of identifiers. Every one of the pictures within the identification list represents a variety of prices, and is more noteworthy than the image that goes before it. As a matter of all, the price of the most countable image is zero. as an example as an example Days

Model :

The concomitant model shows utilization of enum variable − utilizing System;

  • namespace EnumApplication {
  • class EnumProgram {
  • enum Days ;
  • static void Main(string[] args) ”, WeekdayStart);
  • Console.WriteLine(“Friday: ”, WeekdayEnd);
  • Console.ReadKey();
  • }
  • }
  • }

Enums in C# with Examples :

In this article, i will be able to observe Enums in C# with models. Kindly scan our past article wherever we tend to examined Indexers in C# thoroughly. Toward the end of this text, you’ll get what area unit Enums in C# and once and the way to involve Enums in C# sure as shooting models.

For what reason will we actually need Enums in C#?

The Enums area unit specifically names constants. we should always comprehend enums with a model. I actually associate the worker category with the Name and Gender properties. Orientation may be a range.

    1. 1. zero is associate Unknown orientation
    2. 2. 1 is Male
    3. 3. two is feminine

The total model is given below

  • utilizing System;
  • utilizing System.Collections.Generic;
  • namespace EnumsDemo
  • {
  • class Program
  • {
  • static void Main(string[] args)
  • {//Make an assortment to store workers
  • List empList = new List();
  • empList.Add(new Employee() { Name = “Anurag”, Gender = 0});
  • empList.Add(new Employee() { Name = “Pranaya”, Gender = 1 });
  • empList.Add(new Employee() { Name = “Priyanka”, Gender = 2 });
  • empList.Add(new Employee() { Name = “Sambit”, Gender = 3 });
  • //Circle through every workers and print the Name And Gender
  • foreach (var emp in empList)
  • {
  • Console.WriteLine(“Name = {0} && Gender = {1}”, emp.Name,
  • }
  • Console.ReadLine();
  • }
  • //This strategy is utilized to return the Gender public static string GetGender(int orientation)
  • {
  • // The switch here is less meaningful due to these necessary numbers
  • switch (orientation)
  • {
  • case 0:
  • return “Obscure”;
  • case 1:
  • return “Male”;
  • case 2:
  • return “Female”;
  • Default:
  • return “Invalid Data for Gender”;
  • }
  • }
  • }
  • // 0 – Unknown
  • // 1 – Male
  • // 2 – Female
  • public class Employee
  • {
  • public string Name { get; set; }
  • public int Gender { get; set; }
  • }
  • }

At the purpose we have a tendency to|once we|After we} run the program we get the result of faithful kind as displayed below.

The disadvantage of the higher than program is a smaller amount clear even as less viable. This is often on the grounds that it works on integrals as hostile utilizing enums to urge the orientation. Presently we must always understand the way to succeed with these basic numbers with enums to make the program a lot more intelligible and viable. The total model is given beneath.

  • utilizing System;
  • utilizing System.Collections.Generic;
  • namespace EnumsDemo
  • associate degree assortment to store staff
  • List empList = new List();
  • empList.Add(new Employee() );
  • empList.Add(new Employee() one });
  • empList.Add(new Employee() two });
  • empList.Add(new Employee() three });
  • //Circle through each representatives and print the Name and Gender
  • foreach (var emp in empList)
  • && Gender = ”, emp.Name, GetGender(emp.Gender));
  • }
  • Console.ReadLine();
  • }
  • //This technique is used to come the Gender
  • public static string GetGender(int orientation)
  • {
  • // The switch here is presently a lot of clear and viable in lightweight of the very fact that
  • // of replacement the very important numbers with Gender enum
  • switch (orientation)
  • {
  • case (int)Gender.Unknown:
  • return “Obscure”;
  • case (int)Gender.Male:
  • return “Male”;
  • case (int)Gender.Female:
  • return “Female”;
  • Default:
  • return “Invalid information for Gender”;
  • }
  • }
  • }
  • // zero – Unknown
  • // one – Male
  • // a pair of – feminine
  • public category worker
  • public string Name
  • public int Gender
  • }
  • public enum Gender
  • }

Presently after you run the appliance you may get the result faithful kind as displayed beneath. Thus, on the off chance that a program utilizes a bunch of important numbers, think about them as displacement with enums that makes the program additional clear and reparable .

Focuses to recollect concerning C# Enums :-

    1. 1. The Enums area unit lists.
    2. 2. Enums area unit specifically named constants. Later on, associate unequivocal solid is anticipated to vary over from the enum sort to a significant type also because of the different manner around. In addition, associate enum of 1 type can’t be actually allotted to associate enum of 1 additional type despite the actual fact that the basic price of their people are some things similar.
    3. 3. it’s in addition conceivable to change the basic type and upsides of enums.
    4. 4. The Enums area unit esteem varieties.
    5. 5. Enum slogan (every very little letter) is used to form the counts, though the Enum category contains static GetValues() and GetNames() techniques which may be utilized to list Enum elementary type esteems and Names.

Importance of C# Enums :

  • Default basic type is int and also the price beginnings at ZERO
  • The Gender enum basic type is presently short and also the price beginnings from one and is increased by one
  • Thus, for this example, the motivation for Male is two and for feminine, the price is three. The Enum esteems needn’t be in consecutive requests. Any substantial basic type esteem is permissible
  • The incidental enum won’t be aggregated, on the grounds that the best price taken into thought the short info kind is 32767.
  • In the 1st place, create an associate enum for the Gender as displayed at a lower place.
  • Then, at that time, amend the GetGender strategy as displayed at a lower place to enums. Here within the above mentioned, we tend to area units utilizing Enums instead of number integrals that create the code a lot meaty and viable.

C# Enumerations kind – Enum :

In C#, Associate in Nursing enum (or list type) is used to relegate consistent names to a gathering of numeric range qualities. It makes steady qualities a lot of discernible, as an example, WeekDays.Monday is a lot of comprehensible then range zero once alluding to the day in seven days. An enum is characterized utilizing the enum shibboleth, foursquare within a namespace, class, or design. all of the consistent names will be pronounced within the wavy sections and isolated by a comma. The related characterizes Associate in Nursing enum for the non-weekend days.

Model: outline Associate in Nursing Enum

enum WeekDays weekday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }. Over, the WeekDays enum announces people in every line isolated by a comma. Enum Values On the off probability that qualities don’t seem to be relegated to enum people, then, at that time, the compiler can allot range qualities to each half starting with zero as a matter in fact.The principal individual from Associate in Nursing enum are zero, and therefore the value of every progressive enum half is enlarged by one.

Model: Default Enum Values

enum WeekDays weekday,//0 Tuesday,//1 Wednesday,//2 Thursday,//3 Friday,//4 Sabbatum,//5 Sunday//6 }- you’ll be able to allot varied qualities to enum half. Associate in Nursing adjustment of the default value of Associate in Nursing enum half can naturally apportion gradual qualities to completely different people in turn.

Model: Assign Values to Enum Members

enum classes physical science,//0 Food,//1 Automotive = half dozen,//6 Arts,//7 BeautyCare,//8 Fashion//9 }- you’ll be able to even allot numerous qualities to each half.

Model: Assign Values to Enum Members

enum classes physical science = one, Food = 5, Automotive = half dozen, Arts = 10, BeautyCare = eleven, Fashion = fifteen, WomanFashion = fifteen. The enum is of any numeric data type like computer memory unit, sbyte, short, ushort, int, uint, long, or ulong. Be that because it might, associate enum can’t be a string kind.Determine {the sort|the kind|the kind} once enum name as : type. The incidental characterizes the computer memory unit enum.

Model: computer memory unit Enum

enum Categories: computer memory unit physical science = one, Food = 5, Automotive = half dozen, Arts = 10, BeautyCare = eleven, Fashion = fifteen }- Access associate Enum. associate enum is gotten to utilizing the speck language structure: enum.member

Model: Enum Conversion

enum WeekDays Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } Console.WriteLine(WeekDays.Friday);//yield: weekday int day = (int) WeekDays.Friday;//enum to int amendment Console.WriteLine(day);//yield: four power unit wd = (WeekDays) 5;//int to enum transformation Console.WriteLine(wd);//yield: Sat

Hardly any focuses regarding enums :

enums area unit specifically steady. they’re specifically, {for example|for instance|As an example} associate enum of 1 kind might not be verifiably allotted to an enum of 1 a lot of kind despite the very fact that the hidden value of their people area unit one thing similar.enum values area unit fastened. enum is shown as a string and handled as a full range.The default count kind is int, and different supported types are unit byte, byte, ushort, short, long, uint, and ulong. Banners Enumeration offers USA to portion the various qualities to associate enum half or associate enum object.

Benefits of utilizing enums :

  • List offers productive methodology for appointing totally different consistent basic qualities to a solitary variable.
  • List additional develops code clearness and makes program additional easy to stay up with
  • Diminishes mistakes led to by rendering or mistyping numbers.
  • Guarantees forward similarity because it isn’t troublesome to vary constants while not influencing for the duration of the venture.
  • Enums aren’t distributed in memory. They exist simply on the assemblage stage. At the purpose once code runs – there’s no enums there any further.
  • On the off probability that you just Writing the subject Code, you would like to travel for Enum not Const variable String like ‘const sting Word=”Word”‘
  • In my model I actually have used the MS item like Word, surpass and then forth, it clearly tells you that you just have AN clear call of an item within the application, less than that. Another issue, to feature another item, the person in question clearly is aware of wherever to feature this item and the way it tends to be used.

Conclusion :

On the off chance that you just have a call like summation of activity or decisions or conceivable outcomes, you’ll be able to opt for Enum. eg. FileAccess (Read, Write and then on) You will make mistakes in accumulating time itself, not run time, it’s higher and best to follow. As you would possibly be anxious could be price kind and what is more we will modify the Enum esteem as documented during this article. It diminishes the chance of bugs in code one thing like case delicate issues. IntelliSense satisfies you to perform as you possibly are aware of the quantity it’s helpful whereas programming. This can be likewise the simplest utilization of Enum. Once we tend to use Word, in different spots we tend to use words, it’s conflicting also. Assuming you think about it, it helps a lot. You don’t ought to recall the string utterly , merely sort Enum and create a dab that shows the summation.

Are you looking training with Right Jobs?

Contact Us

Popular Courses