The Wayback Machine - https://web.archive.org/web/20160220045047/http://www.codeguru.com:80/columns/dotnet/beginning-c-basic-io-and-variables.html

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.

IO1
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:

IO2
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:

IO3
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.

IO4
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.



About the Author

Peter Shaw

As an early adopter of IT back in the late 1970s to early 1980s, I started out with a humble little 1KB Sinclair ZX81 home computer. Within a very short space of time, this small 1KB machine became a 16KB Tandy TRS-80, followed by an Acorn Electron and, eventually, after going through many other different machines, a 4MB, ARM-powered Acorn A5000. After leaving school and getting involved with DOS-based PCs, I went on to train in many different disciplines in the computer networking and communications industries. After returning to university in the mid-1990s and gaining a Bachelor of Science in Computing for Industry, I now run my own consulting business in the northeast of England called Digital Solutions Computer Software, Ltd. I advise clients at both a hardware and software level in many different IT disciplines, covering a wide range of domain-specific knowledge—from mobile communications and networks right through to geographic information systems and banking and finance.

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Top White Papers and Webcasts

  • Rocket Mobile® for IBM i is an enterprise mobile application development and deployment platform for customers who rely on the IBM i system. Rocket Mobile for IBM i enables customers to leave proven applications in-place and rapidly repurpose them into new managed and secure mobile applications. Fast, easy creation of mobile, web, and hybrid mobile applications that deploy to any iOS, Android, or Windows mobile phone or tablet Built-in integration for seamless repurposing of existing IBM i applications …

  • Microsoft® Office 365 is a top choice for enterprises that want a cloud-based suite of productivity/ collaboration applications. With Office 365, you get access to Microsoft™ Office solutions practically anytime, anywhere, on virtually any device. It's a great option for current Microsoft users who can now build on their experience with Microsoft™ solutions while enjoying the flexibility of a cloud-based delivery. But even organizations with no previous investment in Microsoft will find that …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date