Create an Enum

An enumeration or rather Enum, allows you to restrict your set of options into values that are relevant.

Why use an Enum?
In a situation where we need to create a departmental application, e.g a Software Organization with Developers from different fields: Such as .Net developer, Java Developer, Ruby Developer, etc, In this case, it would be better to use an Enum (and not a magic string) to organize the types we have among this developers within the organization.

Example 1:

       protected void Button1_Click(object sender, EventArgs e)
            var developer = new Engineer();
            hero.Name = heroNameTextBox.Text;

            EngineerType selection;

            if(Enum.TryParse(heroTypeDropDownList.SelectedValue, out selection))
                hero.Type = selection;
            resultLabel.Text += "You selected a " + selection + "!";
    public class Engineer
        public string Name { get; set; }
        public EngineerType Type { get; set; }
    public enum EngineerType
Save and Run:
Diagram showing Enumeration Application 

Example 2

Create a Pet class that uses enum Type for the Pet types instead of a String for the Pet Type.

namespace EnumerationLesson
    public class Pet
          public string Name { get; set; }
          public int Age { get; set; }
            //public string Type { get; set; } // Replaced with PetType Type
          public PetType Type { get; set; }
          private StringBuilder _sb;
            //public Pet(string Name, int Age, string Type)
         public Pet(string Name, int Age, PetType Type)
            this.Name = Name;
            this.Age = Age;
            this.Type = Type;
           _sb = new StringBuilder();
 //Create an enum PetType and replace the string identifier for Type property to PetType.
 // Here is how you create an enum:
        public enum PetType
 Learn also: How to create database

Happy coding!

Follow Maxybyte on social media.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

New Post

New style string formatting in Python

In this section, you will learn the usage of the new style formatting. Learn more here . Python 3 introduced a new way to do string formatti...