C# Enumerations Type Tutorial | Learn Everything about Enum
Enums in C Tutorial ACTE

C# Enumerations Type Tutorial | Learn Everything about Enum

Last updated on 28th Jan 2022, Blog, Tutorials

About author

Manish Kiran (C# Developer )

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

(5.0) | 18621 Ratings 1726
    • C# – Enums Introduction
    • Enums in C# with Examples
    • Focuses to Remember about C# Enums
    • Importance of C# Enums
    • C# Enumerations Type – Enum
    • Hardly any focuses about enums
    • Benefits of utilizing enums
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      C# – Enums Introduction :-

      A specification is a bunch of named number constants. A listed kind is announced utilizing the enum catchphrase. C# lists are esteem information type. All in all, identification contains its own qualities and can’t acquire or can’t pass legacy. Announcing enum Variable

       C# – Enums Introduction
      C# – Enums Introduction

      The overall linguistic structure for announcing a list is −


        enum {

        count list

        };

      Where,

    • The enum_name determines the identification type name.
    • The count list is a comma-isolated rundown of identifiers.

    • Every one of the images in the identification list represents a number worth, one more noteworthy than the image that goes before it. As a matter of course, the worth of the main count image is 0. For instance − enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };


      Model :

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


        namespace EnumApplication {

        class EnumProgram {

        enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

        static void Main(string[] args) {

        int WeekdayStart = (int)Days.Mon;

        int WeekdayEnd = (int)Days.Fri;

        Console.WriteLine(“Monday: {0}”, WeekdayStart);

        Console.WriteLine(“Friday: {0}”, WeekdayEnd);

        Console.ReadKey();

        }

        }

        }


      Enums in C# with Examples :-

      In this article, I will talk about Enums in C# with models. Kindly read our past article where we examined Indexers in C# exhaustively. Toward the finish of this article, you will get what are Enums in C# and when and how to involve Enums in C# for certain models.


    Course Curriculum

    Learn Advanced C and C Plus Plus Certification Training Course to Build Your Skills

    Weekday / Weekend BatchesSee Batch Details

      For what reason do we really want Enums in C#?

      The Enums are specifically names constants. We should comprehend enums with a model. I have an Employee class with the Name and Gender properties. Orientation is a number.

      1. 0 is an Unknown orientation

      2. 1 is Male

      3. 2 is Female

      The total model is given beneath


    Enums in C#
    Enums in C#

        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 Nameand 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 point when we run the program we get the result true to form as displayed beneath.

      The disadvantage of the above program is less decipherable just as less viable. This is on the grounds that it works on integrals as opposed to utilizing enums to get the orientation. Presently we should perceive how to supplant these basic numbers with enums to makes the program more intelligible and viable.

      The total model is given underneath.


        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 representatives and print the Name and Gender

        foreach (var emp in empList)

        {

        Console.WriteLine(“Name = {0} && Gender = {1}”, emp.Name, GetGender(emp.Gender));

        }

        Console.ReadLine();

        }

        //This technique is utilized to return the Gender

        public static string GetGender(int orientation)

        {

        // The switch here is presently more clear and viable in light of the fact that

        // of supplanting the vital 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 Data for Gender”;

        }

        }

        }

        // 0 – Unknown

        // 1 – Male

        // 2 – Female

        public class Employee

        public string Name { get; set; }

        public int Gender { get; set; }

        }

        public enum Gender

        {

        Obscure,

        Male,

        Female

        }

        }


      Presently when you run the application you will get the result true to form as displayed underneath. Thus, on the off chance that a program utilizes a bunch of vital numbers, think of them as supplanting with enums which makes the program more Readable and Maintainable.


    Course Curriculum

    Get JOB Oriented C and C Plus Plus Training for Beginners By MNC Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

      Focuses to Remember about C# Enums :-

      1. The Enums are lists.

      2. Enums are specifically named constants. Subsequently, an unequivocal cast is expected to change over from the enum type to a vital sort as well as the other way around. Additionally, an enum of one sort can’t be certainly alloted to an enum of one more sort despite the fact that the fundamental worth of their individuals is something similar.

      3. It is additionally conceivable to alter the fundamental sort and upsides of enums.

      4. The Enums are esteem types.

      5. Enum catchphrase (every little letter) is utilized to make the counts, though the Enum class, contains static GetValues() and GetNames() techniques which can be utilized to list Enum fundamental sort esteems and Names.


      Importance of C# Enums :-

    • Default basic sort is int and the worth beginnings at ZERO
    • The Gender enum basic sort is currently short and the worth beginnings from 1 and is augmented by 1
    • Thus, for this situation, the incentive for Male is 2 and for Female, the worth is 3. The Enum esteems need not be in consecutive request. Any substantial fundamental sort esteem is permitted
    • The accompanying enum won’t be aggregated, on the grounds that the greatest worth took into consideration the short information type is 32767.
    • In the first place, make an enum for the Gender as displayed beneath.
    • Then, at that point, change the GetGender strategy as displayed beneath to enums. Here in the abovementioned, we are utilizing Enums rather than whole number integrals which make the code more meaningful and viable.

      C# Enumerations Type – Enum :-

      In C#, an enum (or list type) is utilized to relegate consistent names to a gathering of numeric number qualities. It makes steady qualities more discernible, for instance, WeekDays.Monday is more comprehensible then number 0 when alluding to the day in seven days.

      An enum is characterized utilizing the enum catchphrase, straightforwardly inside a namespace, class, or design. Every one of the consistent names can be pronounced inside the wavy sections and isolated by a comma. The accompanying characterizes an enum for the non-weekend days.

      Model: Define an Enum

      enum WeekDays { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }. Over, the WeekDays enum announces individuals in each line isolated by a comma.

      Enum Values

      On the off chance that qualities are not relegated to enum individuals, then, at that point, the compiler will allot number qualities to every part beginning with zero as a matter of course.The principal individual from an enum will be 0, and the worth of each progressive enum part is expanded by 1.

      Model: Default Enum Values

      enum WeekDays { Monday,//0 Tuesday,//1 Wednesday,//2 Thursday,//3 Friday,//4 Saturday,//5 Sunday//6 }- You can allot various qualities to enum part. An adjustment of the default worth of an enum part will naturally allocate gradual qualities to different individuals successively.

      Model: Assign Values to Enum Members

      enum Categories { Electronics,//0 Food,//1 Automotive = 6,//6 Arts,//7 BeautyCare,//8 Fashion//9 }- You can even allot various qualities to every part.

      Model: Assign Values to Enum Members

      enum Categories { Electronics = 1, Food = 5, Automotive = 6, Arts = 10, BeautyCare = 11, Fashion = 15, WomanFashion = 15. The enum can be of any numeric information type like byte, sbyte, short, ushort, int, uint, long, or ulong. Be that as it may, an enum can’t be a string type.Determine the sort after enum name as : type. The accompanying characterizes the byte enum.

      Model: byte Enum

      enum Categories: byte { Electronics = 1, Food = 5, Automotive = 6, Arts = 10, BeautyCare = 11, Fashion = 15 }- Access an Enum. An enum can be 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: Friday int day = (int) WeekDays.Friday;//enum to int change Console.WriteLine(day);//yield: 4 var wd = (WeekDays) 5;//int to enum transformation Console.WriteLine(wd);//yield: Saturday


      Hardly any focuses about enums :-

      enums are specifically steady. They are specifically, for example an enum of one kind may not be verifiably allocated to an enum of one more sort despite the fact that the hidden worth of their individuals are something similar.enum values are fixed. enum can be shown as a string and handled as a whole number.The default count type is int, and other supported sorts are sbyte, byte, ushort, short, long, uint, and ulong. Banners Enumeration gives us to allocate the numerous qualities to an enum part or an enum object.


      Benefits of utilizing enums :-

    • List gives productive method for appointing different consistent fundamental qualities to a solitary variable.
    • List further develops code clearness and makes program more straightforward to keep up with
    • Diminishes mistakes brought about by rendering or mistyping numbers.
    • Guarantees forward similarity as it is not difficult to change constants without influencing all through the venture.
    • Enums are not distributed in memory. They exist just on assemblage stage. At the point when code runs – there is no enums there any longer.
    • On the off chance that you Writing the Architectural Code, You need to go for Enum not Const variable String like ‘const sting Word=”Word”‘
    • In my model I have utilized the MS item like Word, Excel and so forth, it obviously tells you, that you have an unmistakable decision of item in the application, not more than that. Another thing, to add another item, the person in question obviously knows where to add this item and how it tends to be utilized.

    C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion :-

    • On the off chance that you have decision like rundown of activity or choices or conceivable outcomes, you can go for Enum. eg. FileAccess (Read, Write and so on)
    • You will get mistake in accumulate time itself not run time, it is better and best practice.
    • As far as you might be concerned is a worth sort and furthermore we can modify the Enum esteem as referenced in this article.
    • It diminishes the opportunity of Bug in code something like case delicate issue.
    • IntelliSense satisfies you to function as you most likely are aware the amount it is useful while programming. This is likewise the best utilization of Enum. When place we use Word, in other spot we use word, it is conflicting as well. Assuming you consider it, it helps a ton. You don’t need to recall the string completely , simply type Enum and Make a dab it shows the rundown.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free