Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 45 - C# Tutorial - Why Enums

Enums are strongly typed constants. Let's understand enums with an example. I have a customer class with Name and Gender properties. Gender is an integer. 
0 is an Unknown gender
1 is Male
2 is Female

This program is less readable and maintainable, as it operates on integrals instead of using enums.

In the next session we will replace, these integral numbers with enums, which makes the program better readable and maintainable.

Part 45 - C# Tutorial - Why Enums

using System;
public class Enums
    public static void Main()
        Customer[] customers = new Customer[3];
        customers[0] = new Customer()
            Name = "Mark",
            Gender = 1
        customers[1] = new Customer()
            Name = "Mary",
            Gender = 2
        customers[2] = new Customer()
            Name = "Sam",
            Gender = 0
        foreach (Customer customer in customers)
            Console.WriteLine("Name = {0} && Gender = {1}", customer.Name, GetGender(customer.Gender));

    public static string GetGender(int gender)
        // The swicth here is less readable because of these integral numbers
        switch (gender)
            case 0:
                return "Unknown";
            case 1:
                return "Male";
            case 2:
                return "Female";
                return "Invalid Data for Gender";

// 0 - Unknown
// 1 - Male
// 2 - Female

public class Customer
    public string Name { get; set; }
    public int Gender { get; set; }
Please click here, to watch the video on rewriting the above example using enum, which makes the program more readable and mainatainable


  1. give me suggestion for my question - whether break needs to be used in this switch statement!!!!

    1. Return keyword ends the metot. The code lines aren't executed after the return keyword. If you typed after break, you will get a compiler warning as "Unreachable code detected"


If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.