Gigi Labs

Please follow Gigi Labs for the latest articles. Programmer's Ranch no longer has its domain, so please update your bookmarks and links to

Sunday, May 12, 2013

C# Basics: Morse Code Converter Using Dictionaries

Hi all! :)

Today's article is an easy one. We're going to learn to use dictionaries, and use them to make a program that converts text into the Morse Code equivalent.

Just for a change, today I'm going to use Visual Studio 2010 instead of SharpDevelop. If you want to try it, grab an express edition from Microsoft's website. Otherwise, you can manage just as well with SharpDevelop. Let's start off by creating a new console application. In Visual Studio, you can click on the "New Project..." link below the VS logo, or else from the menu, File -> New -> Project...:

Under Visual C# -> Windows, select "Console Application". As with SharpDevelop, specify a name for the project and where to put it. Note: I'm using the Ultimate edition, so your Express edition will be a little different (e.g. less project types).

The sample code given by Visual Studio is a bit different from that of SharpDevelop:

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

namespace CsMorse
    class Program
        static void Main(string[] args)

In particular, there's nothing in Main(). It doesn't matter. However, if you're using SharpDevelop, you're going to need the using System.Collections.Generic; so make sure you add it.

So, now we're going to make a little program based on the Morse Code. In case you don't know, the Morse Code is something that Chuck Norris used to communicate with the aliens who built the pyramids in Egypt. Obviously, he was the one telling them how to construct them.

As you can see from the Wikipedia link in the previous paragraph, each letter of the alphabet has a corresponding representation in Morse as a series of dots and dashes. In order to speed up transmissions, more common characters (e.g. 'E') are much shorter than others.

In C#, we can use a dictionary to map keys (e.g. 'L') to values (e.g. ".-.."). In other programming languages, dictionaries are sometimes called hash tables or maps or associative arrays. The following is an example of a dictionary mapping the first two letters of the alphabet to their Morse equivalents:

            Dictionary<char, String> morse = new Dictionary<char, String>();
            morse.Add('A', ".-");
            morse.Add('B', "-...");


            Console.WriteLine("Press any key...");

First, we are declaring a dictionary. A dictionary is a generic type, so we need to tell in the <> part which data types we are storing. In this case, we have a char key and a String value. We can then add various items, supplying the key and value to the Add() method. Finally, we get values just like we would access an array: using the [] syntax. Just that dictionaries aren't restricted to using integers as keys; you can use any data type you like. Note: you'll know from the previous article, "The ASCII Table (C#)", that a character can be directly converted to an integer. Dictionaries work just as well if you use other data types, such as Strings.

Here is the output:

If you try to access a key that doesn't exist, such as morse['C'], you'll get a KeyNotFoundException. You can check whether a key exists using ContainsKey():

            if (morse.ContainsKey('C'))

OK. Before we build our Morse converter, you should know that there are several ways of populating a dictionary. One is the Add() method we have seen above. Another is to assign values directly:

            morse['A'] = ".-";
            morse['B'] = "-...";

You can also use collection initialiser syntax to set several values at once:

            Dictionary<char, String> morse = new Dictionary<char, String>()
                {'A' , ".-"},
                {'B' , "-..."}

Since we only need to set the Morse mapping once, I'm going to use this method. Don't forget the semicolon at the end! Replace your current code with the following:

            Dictionary<char, String> morse = new Dictionary<char, String>()
                {'A' , ".-"},
                {'B' , "-..."},
                {'C' , "-.-."},
                {'D' , "-.."},
                {'E' , "."},
                {'F' , "..-."},
                {'G' , "--."},
                {'H' , "...."},
                {'I' , ".."},
                {'J' , ".---"},
                {'K' , "-.-"},
                {'L' , ".-.."},
                {'M' , "--"},
                {'N' , "-."},
                {'O' , "---"},
                {'P' , ".--."},
                {'Q' , "--.-"},
                {'R' , ".-."},
                {'S' , "..."},
                {'T' , "-"},
                {'U' , "..-"},
                {'V' , "...-"},
                {'W' , ".--"},
                {'X' , "-..-"},
                {'Y' , "-.--"},
                {'Z' , "--.."},
                {'0' , "-----"},
                {'1' , ".----"},
                {'2' , "..---"},
                {'3' , "...--"},
                {'4' , "....-"},
                {'5' , "....."},
                {'6' , "-...."},
                {'7' , "--..."},
                {'8' , "---.."},
                {'9' , "----."},


            Console.WriteLine("Press any key...");

In the empty space between the dictionary and the Console.WriteLine(), we can now accept user input and convert it to Morse:

            Console.WriteLine("Write something:");
            String input = Console.ReadLine();
            input = input.ToUpper();

            for (int i = 0; i < input.Length; i++)
                if (i > 0)

                char c = input[i];
                if (morse.ContainsKey(c))


Here, the user writes something and it is stored in the input variable. We then convert this to uppercase because the keys in our dictionary are uppercase. Then we loop over each character in the input String, and write its Morse equivalent if it exists. We separate different characters in the Morse output by a forward slash (/). Here's the output:

Awesome! :) In this article we used Visual Studio to create a program that converts alphanumeric text into the Morse-encoded equivalent. In the process, we learned to use dictionaries, and also revisited things like for loops and String methods.

Watch this space for more practical articles! In particular, after a few more articles, we'll be doing some network programming. Some great stuff is coming your way. :)


  1. Error in dictetionary
    is {'2' , "..----"} need {'2' , "..---"}
    and maybe more

    1. Thanks for spotting that one! I've corrected the mistake.

  2. FYI... The dictionary name morse is using the wrong code for the letter S. S = ... (three dots). Good article. Thank you.

  3. thanks it works fine ^^

    it is possible to convert the morse code into a text ?

    1. Of course! Same technique, but backwards.