Start learning free

LESSON 4 OF 347 · WELCOME TO C#

Variables in C#: Declaring and Initializing

Lesson Read the full explanation

In computer science, data is anything that is meaningful to the computer. Java provides a large number of data types, the most frequently used being:

  • int - represents integer numbers like 3 and -12
  • double - represents floating point numbers like 3.14
  • char - represents a single character like 'a', 'Z' or '?'
  • string - represents a sequence of characters like "John Doe"
  • bool - represents one of two values: true or false

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or "123 cats", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables are containers for storing values. A piece of information / data lives in memory and we use a variable to store and descriptively label that data.


Variable declaration:

To create / declare a variable, we must tell C# the variable's data type followed by the variable's name, like so:

string name;

creates a String variable named name.


Variable initialization:

We can initialize a variable to an initial value in the same line as it is created using the assignment operator (=). This code:

string name = "AlgoCademy";

creates a new String variable named name and assigns it an initial value of "AlgoCademy".

When executing this code, C# will allocate some memory, then it will store the string "AlgoCademy" in that memory and finally will attach this name label to that memory location.

You can think of this memory location as a box. In that box, we put string "AlgoCademy". Then, we put the label name on this box.


Accessing values in variables:

Now we can use this label anywhere in our program to access the value in that box. We can print it for example:

// We create and initialize two variables:
string name = "AlgoCademy";
int age = 10;

// We access the variables:
Console.WriteLine(name);
Console.WriteLine(age);

The output of this code is:

AlgoCademy
10

Important notice:

We almost never want to create a variable without initializing it! It's a bad coding practice and can create a lot of problems.


Assignment
Follow the Coding Tutorial and let's create some variables.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    C# · WELCOME TO C#

    Variables in C#, explained

    Data types and variables

    Programs work with data: numbers, text, answers that are true or false. C# is statically typed, which means every piece of data has a type that is known when the program is compiled. The types you'll use most often at the start are:

    TypeHoldsExamples
    intwhole numbers3, -12
    doublenumbers with a fractional part3.14
    chara single character'a', 'Z', '?'
    stringtext"John Doe"
    booltrue or falsetrue, false

    The type matters. The number 12 and the string "12" are different things: you can do arithmetic on the number, but the string is just two characters.

    A variable is a named container for a value. The value lives in memory, and the name is the label you use to get it back. You can picture a box with a label on it, where the box holds the value.

    Declaring a variable

    To declare a variable, write its type and then its name:

    string name;
    

    This creates a string variable called name. In C# the type always comes first.

    Initializing a variable

    You normally give the variable its first value in the same statement, with the assignment operator =:

    string name = "AlgoCademy";
    int age = 10;
    

    Each line reserves memory, stores the value there and attaches the name to it. Reading from the variable is just a matter of using its name:

    string name = "AlgoCademy";
    int age = 10;
    Console.WriteLine(name);
    Console.WriteLine(age);
    
    AlgoCademy
    10
    

    Notice there are no quotes around name inside WriteLine. With quotes, C# would print the word "name" instead of the variable's value.

    Changing a value

    A variable can be assigned again later, as long as the new value has the same type. Leave out the type this time, because the variable already exists:

    int age = 10;
    age = 11;
    Console.WriteLine(age);
    
    11
    

    Gotchas in C#

    • Always initialize. C# won't let you read a local variable that has no value yet. After string name;, the line Console.WriteLine(name); fails to compile with an error like "Use of unassigned local variable 'name'". Giving every variable a starting value avoids the problem.
    • Types must match. int age = "31"; is rejected with "Cannot implicitly convert type 'string' to 'int'". Quotes make text, and an int variable can't hold text.
    • Declare each name once. Writing string a = "x"; string a = "y"; in the same scope is an error. To change the value, assign without the type.
    • Names are case-sensitive. age and Age are two different names. The usual style for local variables is camelCase, such as userName.
    • Pick the right numeric type. An int holds whole numbers up to 2,147,483,647. Going beyond that wraps around silently, and no error is raised. A long holds much larger values.
    • var is not a type of its own. var age = 31; lets the compiler work out the type, here int, from the value. The variable still has a fixed type. This lesson spells the type out, which is clearer when learning.

    The exercise

    You need to create two variables, on two lines:

    1. A string variable named name with the value "Michael". Text goes in double quotes, and the type comes before the name.
    2. An int variable named age with the value 31. A number gets no quotes, because "31" would be a string.
    string name = "Michael";
    int age = 31;
    

    Nothing is printed, because the lesson only asks you to create the variables. To see them, add Console.WriteLine(name); and Console.WriteLine(age);, which print Michael and 31.

    Key takeaways

    • A variable is a named container for a value, and it has a type.
    • Declare it with the type first: type name = value;.
    • Common types are int, double, char, string and bool.
    • Initialize variables when you create them, since C# refuses to read an unassigned one.
    • Reassign with name = newValue;, using a value of the same type.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free