Beginning C#: Basic I/O and Variables
Last month, we saw that you already had everything you needed on your computer that you needed to start writing C# programs. In this post, we're going to take a look at getting input from the user, and doing something with that input.
If you already have Visual Studio of some kind installed, feel free to use that. All of the programs you write will be "Console Mode" programs with nothing special. I'll go over installing Visual Studio in a couple of posts' time; for now, however, I will assume the use of the command line tools introduced last month, and a simple text editor such as Notepad or Notepad++ being used.
Outputting Text
When we left the last post, you'd created a simple program that used
Console.WriteLine("Hello World");
to write some text to the console.
C#, unlike many C-like programming languages, does not have a simple function or keyword for outputting text. Instead, we need to use a .NET library to output our text. It comes as no surprise that this library is called the 'Console' library, and, as can be seen above, it contains a method called 'WriteLine' that is used to output text.
The console library has a number of methods for dealing with simple console operations, 'WriteLine' outputs the text supplied, followed by a newline. Its counterpart 'Write' also outputs the supplied text, but unlike its predecessor, does not output a newline afterwards. 'Write' is used when you want to output multiple items of text on the same line.
As you did last post, create a simple text file called 'Hello2.cs' and make sure it contains the following code:
using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.Write("Hello "); Console.WriteLine("World"); } } }
When you compile and run this using CSC you should see the exact same output as in the previous version.
Figure 1: The same output is produced by using write and writeline
If you want to receive input, the console class also includes 'Read' and 'ReadLine' methods. Read reads the next available character from the console input stream whereas readline reads an entire line followed by a carriage return.
You'll also find that the console class has a method called 'ReadKey'. Readkey differs from read in that it captures a specific keypress. Readkey is used if you're looking for a single specific key, something like a function key, and it returns its data in a special type of data object called a 'KeyInfo' object. Read, like readline, waits for you to press Return to let it know you've entered the key you want to enter; but, unlike readline, it returns the pressed key by using its special numeric code.
Performing a Google search online for "ASCII code chart" will give you a full list of these codes. To get you started, capital A has a code of 65, B has 66, and so on.
I'll describe the difference in more detail in a future post. For now, however, know that there is a difference. If you were producing an onscreen menu, for example, ReadKey would be the appropriate method to use. If, however, you were trying to read a person's initial as part of an input form, read would be your weapon of choice.
Let's try another example. Create a new file called 'input1.cs' and, using your text editor, make sure it has the following code in it:
using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.WriteLine("Hello please enter your name"); string name = Console.ReadLine(); Console.WriteLine("pleased to meet you {0}", name); } } }
Compile it using 'csc input1.cs' and then run it. You should see the following:
Figure 2: Our program can now ask for our name
You'll notice that there's one new thing in the previous code:
string name = Console.ReadLine();
Data and Variables
Any program, large or small, needs to store data. Data is stored in something called a variable. You'll also find variables described as 'fields', 'properties', and 'objects' too, which is used depending on how you design your app. We'll get into this more in later posts once we start to cover object-orientated programming. For now, however, we'll use 'variables' to describe our data holders.
So what's in a variable? Well, in the line above we're telling the C# compiler that we're expecting a string and we want to refer to that variable as 'name'. A string is a sequence of characters that usually spells out a word or a sentence of text.
Strings of text that you add manually are surrounded by quote marks so that the compiler knows where the start and end are, something like the following:
string myText = "This is a string variable";
Variables can also hold numbers. If you wanted to store whole numbers only, you would use an 'int' variable type:
int myNumber = 10;
There are different types of number variables; if you wanted a standard decimal, you'd use the 'decimal' type; if you wanted floating point. you'd use 'float'. We'll cover the differences in number types in more detail later on; for now, we'll use 'int'.
The last simple variable type that I'll introduce you to is the 'boolean'. Booleans (or 'bools') are a very simple variable type that represents only true or false. Booleans are typically used as flags to indicate a yes or a no for something, and are declared as follows:
bool myChoice = false;
Variables are used to store the data you want to work with in your application. Let's now put this into practice.
Create a new file. Let's call this input2.cs, and make sure it has the following code in it.
using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.WriteLine("Hello please enter your name <Remember to press return afterwards>"); string name = Console.ReadLine(); Console.WriteLine("Hello please enter your age {0} <Remember to press return afterwards>", name); int age = int.Parse(Console.ReadLine()); Console.WriteLine("It must be nice to be {0} years old {1}", age, name); Console.WriteLine("Here's a menu for you, please choose wisely then press return."); Console.Write("a) "); // Code for lowercase a is 97 Console.WriteLine(" Choice A"); Console.Write("b) "); // Code for lowercase b is 98 Console.WriteLine(" Choice B"); Console.Write("c) "); // Code for lowercase c is 99 Console.WriteLine(" Choice C"); Console.Write("d) "); // Code for lowercase d is 100 Console.WriteLine(" Choice D"); int menuChoice = Console.Read(); if(menuChoice == 97) { Console.WriteLine("a is a mighty fine choice"); } if (menuChoice == 98) { Console.WriteLine("b is a superb choice"); } if (menuChoice == 99) { Console.WriteLine("c is the best choice"); } if (menuChoice == 100) { Console.WriteLine("d is the last choice"); } } } }
There are a couple of things in there that may be new to you, but don't worry about them at the moment. We'll get to them in future posts once we start to build up our knowledge of C#. For now, however, if everything compiles okay using CSC, you should see something like the following:
Figure 3: The output is more robust now
Before I leave you alone to play with the code, I'll show you one more trick that the console class has.
You can make your programs look a little bit nicer by using a variable, called 'ForegroundColor', inside the console library. By setting this to one of the variables available inside 'ConsoleColor', you can use different colors for different parts of your text.
Create a new file called coloredtext.cs and add the following code.
using System; namespace BlogConsole { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("This is green text"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("This is red text"); Console.ForegroundColor = ConsoleColor.White; } } }
Compile it using CSC and then run it. You should see something similar to the content of Figure 4.
Figure 4: The output text is coloured according to the code's specifications
By using colour statements in appropriate places, you can even have different parts of the same line appear in different colours.
Next month, we'll take a closer look at using variables, and I'll explain how and why you should convert them using methods such as parse to ensure that you get good data.
Until then, happy experimenting.
Comments
There are no comments yet. Be the first to comment!