When it comes to displaying Greek letters all programmers have a problem regardless of the programming language that they're using. There's no keyboard button for the letters that they want to use. For example, a C# application might want to display:
However, initially, they might think that this is not possible, but it is. The secret is to use ASCII codes.
ASCII Codes
ASCII (or the American Standard Code for Information Interchange) codes are simply numbers used to represent letters, numbers and symbols (as well as actions such as carriage returns and tabs). The Greek alphabet occupies two distinct ranges in this set of ASCII codes. These are:
- 913 to 936 = upper case Greek letters
- 945 to 968 = lower case Greek letters
It's then just a matter of getting C# to interpret these codes correctly
Interpreting ASCII Codes with C#
C#, of course, comes with a relatively simple way of converting the code (in the form of an integer) into a Greek letter:
If the programmer runs this code then they will see π displayed on the screen, and this simple technique can be extended to output the full alphabet to a text file.
Using the Correct C# Namespaces
As always the first step to creating a C# application is to define the namespaces that will be used. The simplest console application will at least require the System namespace:
And, in this case, a file will be written to, and so the IO namespace will be needed as
well:
The programmer is now ready to create the new C# class.
Setting Up the Class Parameters
Rather than hard coding numbers throughout the application, it is much more efficient to define them at the start of the class. For example, the start of the ASCII range can be set:
And then the offset between the upper and lower case letters:
And finally the list of Greek letter names:
These can all be used in the application in order to display the letters correctly.
Creating an Output File
The aim of this command line application is to write the complete Greek alphabet to a file, and so the first step is to define the file name:
And then to ensure that the file does not already exist:
Next, the code creates the file:
And then it opens the file so that it is ready to be written to:
The file is now ready to receive the alphabet.
Writing the Greek Alphabet to a File with C#
The class information about the Greek alphabet are used in a loop:
The code then uses the loop index to define the ASCII codes and the results can be written to the file:
And finally the file must be closed:
If the application is compiled and run at this point (as shown in figure 1 at the bottom of this article) then a new file will be created. If the application user examines this file (as shown in figure 2) then they will find that it contains the complete Greek alphabet, both in upper and lower case, and with the correct letter name.