Lesson 1.2 Concept of a variable

Remember the example of the sum we went over earlier? This is where variables come in. They are a handy way of holding values in memory. They are an arbitrarily named bit of memory to do with as you please. Clear as mud, I’m sure. It’s a bit of an abstract concept that really only becomes obvious when actually used. But how can you use it if you don’t understand it? Chicken and egg isn’t it? Well, an example is a stab in the right direction.

Consider this modified Hello World example. 

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

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string message = "Hello World";
            System.Console.WriteLine(message);
            System.Console.ReadKey(true);

        }
    }

 The message itself can be placed into a variable. The added line takes the message and places it into a variable.  This process of creating a variable is known as declaring. It tells C# that you have decided to use a new variable and this is its name. In this case we are creating a variable called “message” and giving it the value “Hello World”. The word “string” is explained in the next section.

  string message = "Hello World!";

The next line, instead of reading out the text directly, uses the variable instead.

  System.Console.WriteLine(message);

Remember, this used to have

  System.Console.WriteLine("Hello World!");

While I have cannily named the variable “message” you could call it “note”, “missive” or even “sausage”; whatever you please. Well almost, there are some simple rules to follow when naming a variable:

  • it must only contain alphanumeric, that is a letter or number, characters
  • it cannot begin with a number, although numbers can be in it
  • variable names are case sensitive

By now you should be able to see what variables are. Their purpose is not immediately obvious even if their use is. I have to confess when I was first shown their use back on the ZX Spectrum I was nonplussed. So what? They’re nice, what are they for?

I will go on to rundown the variables I feel are most commonly used. The next section after that will begin to show how they’re actually used in coding.