1.0: Variables

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

Variables Defined

A variable is a name given to a storage container that our program can use and manipulate. C# is a typed language, which means that a variable in C# has a specific type. The type determines the size and layout of the variable's memory. The variable type also helps define the range of values that can be stored in memory. Think of it as a container for holding items.

Declaring and Initializing Variables

Let's look at how to declare variables: 1. To declare a variable, you need a type and a name for your variable 2. The type will be something like int or string 3. Variables will be camel cased in C#. First word is lowercase, and each subsequent word will be uppercase.

  • birthYear or isMarried

    1. The name is up to you, but it should be descriptive enough that you can easily remember what it's for.

Declaration

Here is an example of declaring a variable:

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

Here we've only declared a variable. We are saying there is a thing called birthYear and the value type is an int, but we have not assigned the value.

Initialization

To initialize a variable, you need to give it a value. You can initialize the variable on the same line that you declare it, or later, on another line. Consider the following

static void Main(string[] args)
{
  //  1       2         3
  int birthYear = 1990;

  int age;
  age = 41;
}
  1. Data type

  2. Variable name

  3. Value associated to data type

Practice

In your Program.cs file in the DataTypes project, practice declaring and initializing variables of type string or type int. Make one for age, firstName, lastName, numberOfKids, etc.

Next: Data Types

Last updated