Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 46 - C# Tutorial - Enums Example


Part 46 - C# Tutorial - Enums Example


The program that we have started in Part 45 is now rewritten using Gender enum, which makes it more readable and maintainable.


If you have not watched video on problems of not using enums, please click here to watch it now


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


    public static string GetGender(Gender gender)
    {
        // The swicth here is now more readable and maintainable because 
        // of replacing the integral numbers with Gender enum
        switch (gender)
        {
            case Gender.Unknown:
                return "Unknown";
            case Gender.Male:
                return "Male";
            case Gender.Female:
                return "Female";
            default:
                return "Invalid Data for Gender";
        }
    }
}


public enum Gender
{
    Unknown = 0,
    Male = 1,
    Female = 2
}


public class Customer
{
    public string Name { get; set; }
    public Gender Gender { get; set; }
}

3 comments:

  1. Best place to learn C# basic so far.

    ReplyDelete
  2. Dear Sir
    Why we are use this function(GetGender) because already
    we use (enum Gender),the program working without this function
    we need remove (GetGender(customer.Gender)) and use only
    (customer.Gender))
    Thanks

    ReplyDelete
  3. Sir.. Should we still require the method GetGender in this example ? Can't we pass Customer.Gender directly in the Console.writeLine statement ?

    ReplyDelete

It would be great if you can help share these free resources