Intro to C# – Switches and Errors

Hello World!

One of my good friends is going through a reskill to become a software developer, so I have decided to help him out, because, isn’t that really my job? Help everybody be successful with programming? Anyways, this has provided some new insight into challenges people face learning to code that you just don’t remember as a seasoned developer. Anyways, he was working through some code and sent me his code to look over. I want to go over both code bases and why I chose to change even code as simple as that to what it has become. The code written derives from the Microsoft Virtual Academy Intro to C# series, located here.

What he emailed me:

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

namespace Decisions
    class Program
        static void Main(string[] args)
            Console.WriteLine("Would you prefer what is behind door number 1, 2, or 3");
            string userValue = Console.ReadLine();
            string message = (userValue == "1") ? "boat" : "stran of lint";
            Console.WriteLine("You won a {0}", message);

What I changed it to:

using System;

namespace Decisions
    public class Program
        static void Main(string[] args)
            //create a completion flag
            bool amDone = false;
            //keep asking the user to enter info until you get something value.
                //assign the result of your function to am done.
                amDone = Program.DoStuff(); //executes DoStuff, and assigns the resulting value to am done.
        /// <summary>
        /// DoStuff is a static function within the class Program.  Program does not need to be instantiated
        /// as an object to call this, It is a function that should not rely on the state of an instance of Program
        /// All static properties and functions are shared by instances of the program object.
        /// </summary>
        /// <returns>boolean value, true or false.  
        /// All logic paths must return either true or false.</returns>
        public static bool DoStuff()
            Console.WriteLine("Which door would you like to choose? 1, 2 or 3?");
            //Get your input as a console string.
            string s = Console.ReadLine();
            int k;
            //ALWAYS safely validate anything that comes from a user or another system.
            //safely convert string s to k.
            //the out key word indicates it will overwrite 
            //the primitive value of k
            //if s cannot be converted, k will be 0.
            int.TryParse(s, out k);
            //create an empty memory location for message.
            string message;
            switch (k) //Enter into the scope of the switch statement.
                case 1: message = "You won a new car!"; //if k == 1, then message will be this.
                    break; //break out of statement and continue executing after switch.
                case 2: message = "You won a new boat!"; //read above except for 2.
                case 3: message = "You won a cat!"; // read above except for 3.
                    Console.WriteLine("Please type 1, 2 or 3.  As an integer value only.");
                    return false; //If the value is not matched in the switch, it comes here.
                    //return indicates, we will stop processing this function and return the value "false"
                    //which is of type bool.
            Console.WriteLine("You won a {0}", message); //write the message
            Console.ReadKey(); //push any button to continue
            return true;
            //indicates we are done with the function, we will return the value true, which is of type bool.

Reasons for changes

The biggest thing you will notice is that the code I wrote is covered in comments.  This is more for your benefit, I comment my code, but not nearly like that.  So lets break down the real changes…

  1. Error Handling.  In the original code, if the user enters a bad value the user gets a string of lint, however the only valid options are doors 1, 2 or 3.  I suppose this is a decent option, however in reality, we might want to force a correct answer, or do something more with it.  The Boolean true false is not necessarily what you want to do.  So to add error handling, I have extracted the core functionality into its own function, “DoStuff”.  DoStuff returns true or false, yes or no did the user give me good data in which I could process correctly.  If yes, then we can end the program, else, make the user enter something useful.  Also you will notice that I use this try parse thing.  Valid answers are 1, 2 or 3 only, so we want to safely convert into a value that can be switched on without possibly throwing an exception.  The “out” keyword simply means the value coming in, will be overwritten when it comes out.
  2. Switch Statement.  In the original code, there was simply an if/else, however there are 3 options for doors.  This is more easily handled and cleanly handled with a switch statement.  You can also easily add more doors with a switch.  So we are correctly handling the number of potential options and keeping the code clean for expansion later.

Notes:  The “out” keyword can not be used on just any parameter, the function will explicitly state which parameters MUST have the out keyword.  out is not really a consumer option, but rather an api provider requirement.


So there we have it.  We covered basic error handling and switch statements.  Remember, ALWAYS error check any values that are derived from the outside world or can be impacted by “side effects” and handle those in a way that makes sense for your program.  We also showed the conversion from entry level code to something more production ready.

One thought on “Intro to C# – Switches and Errors

  1. This was a very good read! Much easier to dissect with all the notes in the code. The code you used in place seemed more efficient and I was able to understand the majority of everything you used in the new code!

Leave a Reply

Your email address will not be published. Required fields are marked *