News

Copyright © 2008-2019 Paula DiTallo

Tag Cloud



C# Crash Course Series: Why Use the Enum Type?

What is an Enum Type?

At first glance, a custom enumeration may look like the old C/C++ struct type, but they are not (we'll talk about those later, since struct types still exist).  Think of enums as a way to define named constants that correspond to numerical values. The default value, if you chose NOT to assign a value to a constant name is "0". However many constants you create, the next one on the list will take the next number. If you start your first constant with a number like 1000, the next constant will be assigned the number 1001. You can however, assign any number you please in any order, as long as you don't assign the same number twice.

    // default assignment of numerical vals
    enum CleaningProds
    {
        Clorox,      // default value begins with 0
        OxiClean,    // = 1
        Fantastic,   // = 2
        SimpleGreen  // = 3
    }

    // default assignment of numerical vals, after 1st assignment
    enum CleaningProds
    {
        Clorox = 1000,      // default value begins with this assignment
        OxiClean,    // = 1001
        Fantastic,   // = 1002
        SimpleGreen  // = 1003
    }

    // direct assignments-- ordered as you like.
    enum CleaningProds
    {
        Clorox = 100,
        OxiClean = 10,
        Fantastic = 18,
        SimpleGreen = 8000
    }

 

Why Use an Enum Type?

Since we are basically creating our own user-defined types with enums, we could use them as a way to case through available known values against an input value.

Since this is a political year in the USA, I thought I would use an enum called PoliticianType. I took a handful of past and present  US political parties and made up what the theoretical candidates from these parties might say regarding the topic of unemployment based on the PoliticianType parsed from a user's input string. Cut and paste this example into a Visual Studio C# Console application to see what the candidates say!

For example, here's what you should see if you enter libertarian

 

 

// ------------------------------------------ Enum Type Sample Console Project -----------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AskPaulaCSharpProject
{
    class CSharpSampling
    {
     
        enum PoliticianType
        {
            knownothing,
            whig,
            federalist,
            republican,
            democrat,
            wspus,
            libertarian,
            teaparty,
            greenparty,
            unknown     //dubbed
        }

        static void Main(string[] args)
        {
            Console.WriteLine("------ Welcome to The Joy of Political Platform Guessing ------\n");
            Console.WriteLine("The topic is a theoretical politician's views on unemployment benefits based on the political party affiliation.\n");
            Console.WriteLine("Possible choices: knownothing,whig,federalist,republican,democrat,wspus,libertarian,teaparty,greenparty.\n");
            Console.WriteLine("------ Have FUN! -----------------------------------------------\n");

            //Let's get started with collecting and displaying info

            Console.Write("Which political party? (press CTRL+Z to exit): ");
            string political_party = Console.ReadLine();

            Console.Write("The, " + political_party + " party it is! \n");
            //convert the string input to an enumerated type
           
            try
            {
                PoliticianType party = (PoliticianType)Enum.Parse(typeof(PoliticianType), political_party, true);
                PositionOnUnemployment(party);
            }
            catch (Exception e)
            {

                try
                {
                    // the most likely exception is a string with
                    // no Enum type match after the parsing. Let's fix that
                    // here.
                    Console.WriteLine("reprocessing due to error: " + e.Message + "\n");

                    political_party = "unknown";
                    PoliticianType party = (PoliticianType)Enum.Parse(typeof(PoliticianType), political_party, true);
                    PositionOnUnemployment(party);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("There is an error: " + ex.Message + " \n");
                }
            }

        }
        static void PositionOnUnemployment(PoliticianType p)
        {
            switch (p)
            {
                case PoliticianType.democrat:
                    /**
                     * Supporting references for position
                     * ----------------------------------------
                     * too much to list!;-)
                     * ----------------------------------------
                     * reference: http://en.wikipedia.org/wiki/Democratic_Party_(United_States)
                     **/
                    Console.WriteLine("Candidate C. Me Beeks DuppleSpeaks says:\n");
                    Console.WriteLine("The issue of unemployment is one of Republican policy\t");
                    Console.WriteLine("To end unemployment, we must stimulate the economy with last-resort \t");
                    Console.WriteLine("government spending. On the other hand, there is some merit to the \t");
                    Console.WriteLine("argument that generous unemployment insurance benefits discourage \t");
                    Console.WriteLine("a person to aggressively seek employment. However, in economic times \t");
                    Console.WriteLine("like these, it is necessary to extend the minimum of benefits for a longer \t");
                    Console.WriteLine("period to encourage consumer spending.\t");
                    break;
                case PoliticianType.federalist:
                    /**
                     * ----------------------------------------------
                     * reference: http://en.wikipedia.org/wiki/Federalist_Party
                     **/
                    Console.WriteLine("Candidate C. Reason says:\n");
                    Console.WriteLine("The issue of unemployment must be examined in terms of \t");
                    Console.WriteLine("available capital and the policies surrounding national lending \t");
                    Console.WriteLine("to industries and individuals committed to workforce investment.\t");
                    break;
                case PoliticianType.knownothing:
                case PoliticianType.teaparty:
                    /**
                     * reference: http://en.wikipedia.org/wiki/Know_Nothing
                     * http://en.wikipedia.org/wiki/Boston_Tea_Party_(political_party)
                     *
                     **/
                    Console.WriteLine("Candidate Ida Noe says:\n");
                    Console.WriteLine("Unemployment could be best solved by eliminating\t");
                    Console.WriteLine("the presence of illegal immigrants.\t");
                    break;
                case PoliticianType.libertarian:
                    /**
                     * --------------------------------------------------------
                     * reference:http://en.wikipedia.org/wiki/Libertarian_Party_(United_States)
                     **/
                    Console.WriteLine("Candidate Yorr Rites:\n");
                    Console.WriteLine("Unemployment should be treated like an accute infection.\t");
                    Console.WriteLine("A strong injection of non-government intervention in the markets and trade.\t");
                    break;
                case PoliticianType.greenparty:
                    /**
                     * -------------------------------------------------------------
                     * reference: http://en.wikipedia.org/wiki/Green_Party_(United_States)
                     * http://www.gp.org/platform/2004/economics.html
                     *
                     **/
                    Console.WriteLine("Candidate Saath DaWales:\n");
                    Console.WriteLine("We must challenge the current status quo by insisting\t");
                    Console.WriteLine("on investing in the local, environmentally safe production of goods\t");
              
                    break;
                case PoliticianType.republican:
                    /**
                     * reference: http://en.wikipedia.org/wiki/Republican_Party_(United_States)
                     *
                     **/
                    Console.WriteLine("Candidate Rapp Tin DeFlagge:\n");
                    Console.WriteLine("Unemployment benefits will only assure that there will always be more unemployment.\t");
                    break;
                case PoliticianType.whig:
                    /**
                     * ---------------------------------------------
                     * reference: http://en.wikipedia.org/wiki/Whig_Party_(United_States)
                    **/
                    Console.WriteLine("Candidate Les S. PruGress says:\n");
                    Console.WriteLine("Unemployment benefits need not be the issue. Instead, we must\t");
                    Console.WriteLine("as a nation, assure honest labor. We must expand our nation's ambitions for improvement.\t");
                    Console.WriteLine("We must re-examine foreign investments to discourage \t");
                    Console.WriteLine("the shrinking position of American manufactoring and productivity.\t");
                    break;
                case PoliticianType.wspus:
                    /**
                     * -------------------------------------------------
                     * reference: http://en.wikipedia.org/wiki/World_Socialist_Party_of_the_United_States
                    **/
                    Console.WriteLine("Candiate Verkka Sue Night says:\n");
                    Console.WriteLine("Until we as a united people discard the notion of our individual earning potential as a privilege\t");
                    Console.WriteLine("based on circumstance and influence, in favor of producing and exchanging needed goods and services,\t");
                    Console.WriteLine("the issue of unemployment will loom larger than the joy of the time not spent\t");
                    Console.WriteLine("in forced daily engagement.\t");
                    break;

                default: //deal with anything else entered
                    Console.WriteLine("Not a known party at this time. Try again!\n");
                    break;

            } //end of switch case
        }
 
    }

}
 

Saturday, August 28, 2010 11:00 PM

Feedback

# re: C# Crash Course Series: Why Use the Enum Type?

Thats what i was looking.! THX 1/16/2011 8:34 PM | Johnny

Post A Comment
Title:
Name:
Email:
Comment:
Verification: