2.0: Variables

In this module we'll discuss declaring and initializing variables.

File Location

  1. Right click on the solution you made in the first module, go to Add > New Project.

  2. Select Console App (.NET Framework).

  3. Name it 02_variables.

  4. You will write your code for this module within Program.cs of that project. Go ahead and open that file now.

Declaring and Initializing Variables

Let's look at how to declare variables:

Here is some code:

class Program
{
    static void Main(string[] args)
    {
        //1    //2          //3
        string firstName = "Paul";
        Console.WriteLine(firstName);
        Console.ReadLine();
    }
}
  1. To declare a variable, you need a type. In this case, we are using a string type. More on types later.

  2. We also need a name for the variable. In this case it isfirstName. The name of the variable is up to you. A few considerations:

    • It should be descriptive enough that you can easily remember what it's for, but not too long.

    • It will be camelCased i.e. birthYear or isMarried. This means that the first word is lowercase and each subsequent word is uppercase.

  3. We also initialize the value of the variable with a string value in quotes.

Declaration Only

There are times when we will only want to declare a variable.

class Program
{
    static void Main(string[] args)
    {
        string firstName = "Paul";
        Console.WriteLine(firstName);
        //1       //2
        string lastName;
                        //3
        Console.WriteLine(lastName);

        Console.ReadLine();
    }
}

We are saying there is a thing called birthYear and the value type is an int, but we have not assigned the value:

  • To initialize a variable, you need a type, a name, and a value.

  • You can initialize the variable on the same line that you declare it, or later, on another line.

static void Main(string[] args)
{
    int birthYear = 1990;
}

In your Program.cs file in the 02_variables project, practice declaring and initializing variables of different types with different variable names and values.

Last updated