C# Variables & Constants Tutorial

In this tutorial we learn about simple data containers in C# called variables and constants.

We cover how to create variables and constants, how to assign data to variables and constants and the var automatic type as well as Lvalues and Rvalues.

What is a variable

When a program is running it needs to work with data. For example, a calculator would need to store the numbers a user inputs to be able to do some calculations.

This data is temporarily stored in the memory (RAM) of your computer throughout the life of the program. When the program stops running, the data is removed from memory.

We store this data into data containers like variables and constants. Think of a variable as a little box.

  • You can place something inside the box.
  • You can remove the contents at any time to work with.
  • You can change the contents inside the box at any time.
  • You can give the box to someone else so that they can do things with it.

In C# we can only store one type of thing in a box, for example, a box can only hold shoes. If we wanted to put socks in there as well we would need a new seperate box for them.

We also need to write on the box what type of content it will hold and give the box a name.

How to create (declare) a variable

To create a variable, we declare it. First, we specify the type of data it will hold, then we give the variable a name.

Syntax:
 type indentifier;
Example:
using System;

class Program
{
    static void Main(string[] args)
    {
        int shoes;
    }
}

In the example above, we declared a variable called shoes. The type of data it will hold is full numbers, or integers, so we use the keyword int as the type.

The statement reads: declare a variable named shoes of type int

We can only store integers in this variable from now on. We can’t store, for example, chars like “Hello World”.

How to assign data to a variable

At this point we have an empty box, ready for something to be placed inside it. To assign data to a variable, we use the assignment operator ( = ).

We write the variable name, followed by the = operator, and then the value that we want to store.

Syntax:
 indentifier = value;
Example:
using System;

class Program
{
    static void Main(string[] args)
    {
        int shoes;
        shoes = 10;
    }
}

In the example above, we assign the value of 10 to the variable shoes.

The statement reads: set the value of shoes equal to 10

We don’t specify the type again. That’s because the variable already exists and so the compiler will know its type. The declaration is only done once but we can assign values to it as much as we like.

Example:
using System;

class Program
{
    static void Main(string[] args)
    {
        int shoes;

        shoes = 10;
        shoes = 12;
        shoes = 16;
    }
}

In the example above, we changed the value from 10 to 12 and then from 12 to 16. Now the value of shoes will be 16 and no longer 10.

How to initialize a variable

We can declare a variable and assign data to it in one step. This is known as initializing a variable.

To initialize a variable, we assign a value to it when it’s being declared.

Syntax:
 type indentifier = value;
Example:
using System;

class Program
{
    static void Main(string[] args)
    {
        int shoes = 10;
    }
}

In the example above, we create a variable named shoes, with a value of 10.

The statement reads: declare a variable named shoes of type int with a value of 10

How to initialize a variable inline

If we know that multiple variables will have the same type we can declare them inline.

Example:
 type name1, name2 = 10, name3 = 20;

We declare or initialize our variables as we would normally. Except, this time we only specify the type once and separate each declaration or initialization with a comma.

Example:
using System;

class Program
{
    static void Main(string[] args)
    {
        int laces, shoes = 10, socks = 20;
    }
}

The inline initialization example above, would be the same as writing the following.

Example:
using System;

class Program
{
    static void Main(string[] args)
    {
        int laces;
        int shoes = 10;
        int socks = 20;
    }
}

How to use var as an automatic type

Some variables in C# may be initialized without an explicit type. The compiler will look at the data in the variable and determine its type automatically.

We replace the type with the keyword var .

Example:
// compiled as an int
var shoes = 10;

// compiled as a string
var message = "Hello";

// compiled as int array
var numbers = new[] { 0, 1, 2 };

// compiled as List<int>
var list = new List<int>();

We are only allowed to use var locally. That means that they can only be used inside functions.

Example:
using System;

class Program
{
    // outside function, illegal
    var socks = 20;

    static void Main(string[] args)
    {
        // inside function, legal
        var shoes = 10;
    }
}

Another rule about var is that it must be initialized with a value. A var cannot be empty when it’s declared.

Var and floating point numbers

When we use var with a floating point number, it will automatically use double with its precision. If we wanted a float, we would have to declare a float type explicitly.

Example:
 var num = 4.999999999999995;

Operands, Lvalues and Rvalues

There are two kinds of expressions in C#:

  • Lvalues. Operands on the left or right of the assignment operator.
  • Rvalues. Operands on the right of the assignment operator only.

Lvalues

An lvalue can have a value assigned to it. It can also be used to assign a value to something else. So, it’s allowed to appear on the left and right side of the assignment operator.

A typical example of an lvalue would be a variable.

Example:
// lvalue may be on the left (var1)
int var1 = 10;

// or on the right of the =
int var2 = var1;

In the example above, the lvalue is var1.

Rvalues

An rvalue cannot have a value assigned to it. It may only appear on the right side of an assignment operator.

A typical example of a rvalue would be a number, such as 10 or 20.

Example:
// rvalue may only be on the right (10)
int var1 = 10;

// and cannot be on the left
int 10 = 10;

In the example above, the rvalue is 10.

What is a constant

Constants are almost exactly the same as variables, the only differences are:

  • A constant’s value cannot change during runtime, it’s immutable.
  • A constant is declared with the const keyword before the type.
  • A constant must be initialized, that’s to say, it must have a value when declared.
Example:
 const float pi = 3.14f;

The value of the pi constant in the example above cannot be changed while the application is running.

We use constants for safety in our applications. We may not want certain values to be accidentally changed at runtime, like the value of Pi, or gravity.

Summary: Points to remember

  • A variable is a mutable data container that will temporarily hold our application’s data through runtime.
  • We must specify the type of data that a variable will hold when declaring or initializing it.
    • We can use the automatic type var to let the compiler infer the type from the contents of the variable.
  • A constant is an immutable data container and is used when we don’t want data to change at runtime.
  • The two types of expressions in C# are Lvalues and Rvalues
    • Lvalues are the operands on the left of the = operator.
    • Rvalues are the operands on the right of the = operator.