Using Variables

[print-me]

Variables in C# are containers inside the computer’s memory where you can place the data you need for your program. The term “variable” got its name from the fact that variables represent values that change. The data stored in these variables have different types called data types which determine the type of data a variable can store. For example, a variable with an int data type can only store whole numbers and a variable with a string data type can store string literals.variable examples 1 demonstrates how you can declare and assign values to the variables.

using System;
 
namespace VariableDemo
{
    class Program
    {
        public static void Main()
        {
            //Declare variables 
            int num1;
            int num2;
            double num3;
            double num4;
            bool boolVal;
            char myChar;
            string message;
 
            //Assign values to variables 
            num1 = 1;
            num2 = 2;
            num3 = 3.54;
            num4 = 4.12;
            boolVal = true;
            myChar = 'R';
            message = "Hello World!";
 
            //Show the values of the variables 
            Console.WriteLine("num1 = {0}", num1);
            Console.WriteLine("num2 = {0}", num2);
            Console.WriteLine("num3 = {0}", num3);
            Console.WriteLine("num4 = {0}", num4);
            Console.WriteLine("boolVal = {0}", boolVal);
            Console.WriteLine("myChar = {0}", myChar);
            Console.WriteLine("message = {0}", message);
        }
    }
}
num1 = 1
num2 = 2
num3 = 3.54
num4 = 4.12
boolVal = true
myChar = R
message = Hello World!

Declaring Variables


Lines 10-16 declared variables with different data types and identifiers.

int num1;
int num2;
double num3;
double num4;
bool boolVal;
char myChar;
string message;

Declaring variable is the way of telling the program that it is available for use and what datatype it will accept. Always keep in mind that you need to declare variables first before you can use or assign values to them. Otherwise, you will encounter a compile-time error. When declaring variables, you need to indicate the data type followed by its identifier. It is then terminated by a semicolon. Declaration of variables is simply called declaration. The following is the syntax of declaring a variable:

data_type identifier;

The data_type is the data type of the variable such as intdouble or char. The identifier is the valid name of the variable and is used to access the variables content, add a new value to it, or modify the existing value of that variable.

You can also declare multiple variables with the same data type in just one line. It uses the following syntax:

data_type identifier1, identifier2, ... indentifierN;

Take a look at the following example:

int num1, num2, num3, num4, num5;
string message1, message2, message3;

The above declaration statements declare five integer variables and three string variables. We simply indicate the data type and a comma-separated list of identifiers.

 

Naming Variables


An identifier must start with an alphabet or an underscore. It is then optionally followed by alphabet or numbers. You cannot use special characters such as #, %, &, or start the identifier name with a number such as 2numbers. Identifiers can’t contain spaces. As a workaround for multiple word names, you can use underscore(_) instead of space (you can’t use the  sign). The following are examples of valid variable names.

num1  myNumber  studentCount  total       first_name    _minimum
num2  myChar    average       amountDue   last_name     _maximum
name  counter   sum           isLeapYear  color_of_car  _age

The following are examples of invalid names for identifiers.

123        #numbers#  #ofstudents  1abc2
123abc     $money     first name   ty.np  
my number  this&that  last name    1:00

If you look at the examples of valid variable names, you will notice a convention used when naming them. Identifiers for variables uses camel casing. Camel Casing is a naming practice where the first letter of the first word should be a small letter and each succeeding letters are small letters. For multiple-word variables, each succeeding word must have their first letter capitalized. For example, the identifier myNumber contains the words “my” and “number”. Notice that the first letter of the word number in the identifier is capitalized. Another example is numberOfStudentsWhoGraduated which is quite a long name that uses camel casing. Notice how each word after the first word has their first letter capitalized. More naming conventions will be introduced to you as we progress to future lessons.

Variable Scope


Notice that the variables are declared inside the block of the Main method. This limits these variables to be only accessible or usable inside the Main method. This is called scope which determines where in the code, variables can be used. Once the program reaches the end of the Main method, these variables go out of scope and becomes unusable while the program is running. There are more types of scopes. You will learn more about scopes in a later lesson. Determining the scope of variables is important so you can determine where in your code a variable is valid. Another reason is that, two or more variables within the same scope cannot have an exact same name or identifier. The following will produce an error:

int num1;
double num1;

Notice that even though the two variables have different datatypes, they still have the same identifier. This is a typical error and you will get an error message when compiling saying “A local variable named ‘num1’ is already defined in this scope”. But because C# is case sensitive, you can provide the same identifiers in the same scope as long as they have different cases. The following three variables are actually three different variables and will be accepted by the compiler.

int num1;
int Num1;
int NUM1;

Although this is valid, it is not recommended as it can cause confusion on your side and on others who will look at your code plus the last 2 identifiers break the naming convention for local-scoped variables.

Initializing Variables


You can assign values to variables immediately after they have been declared in the program. This is called initialization. The following is the basic syntax of intializing a variable with a value.

data_type identifier = value;

For example:

int myNumber = 7;

You can also initialize multiple variables. Simply seperate them with a comma.

data_type variable1 = value1, varaible2 = value2, ... variableN, valueN;
int num1 = 1, num2 = 2, num3 = 3;

It is nice to know the difference of declaration and initialization. Declaration simply declares the method by specifying the data type and the name of the identifier. If you try to use an undeclared variable, then you will receive an error message “Use of unassigned local variable ‘myVariable'” where myVariable is the name of the unassigned variable. Initialization is similar to declaration but values are assigned to the declared variables. This gives a variable an “initial value” hence the term initialization.

Assigning Variables with Values


Assigning a value to a variable is placing a value inside that variable. If the variable has contents already, then it will be overwritten. Think of it as putting some contents to a container and removing it’s previous content if it is not empty. When assigning variables with a value, you use the following syntax.

variable = value;

You indicated the name of the variable followed by the assignment operator which is represented by the = sign then followed by the value to be assigned to the variable. The left of the assignment operator is often called an l-value (left value) while the right side of the assignment operator is often called r-value (right value).

Lines 19-25 of Example 1 assigns values to each variables that we have declared.

num1 = 1; 
num2 = 2; 
num3 = 3.54; 
num4 = 4.12; 
boolVal = true; 
myChar = 'R'; 
message = "Hello World!";

Note that we cannot assign values to variables that has not been declared yet. You can only assign values to variables that are valid and can be accepted by the data type of the variable. For example, num1 and num2 are both declared int so they can only accept integers as values. boolVal was declared bool so it can only accept either values true or falsemessage was declared as string so it can only accept a string literal. Failing to assign valid values for the variable’s datatype will lead to errors.

Format Placeholders


You noticed the new version of the WriteLine() method (lines 28-34).

Console.WriteLine("num1 = {0}", num1);
Console.WriteLine("num2 = {0}", num2);
Console.WriteLine("num3 = {0}", num3);
Console.WriteLine("num4 = {0}", num4);
Console.WriteLine("boolVal = {0}", boolVal);
Console.WriteLine("myChar = {0}", myChar);
Console.WriteLine("message = {0}", message);

It now accepts two arguments. Arguments are the information needed by a method before performing its job. The method in this case is WriteLine. Arguments are seperated by a comma. The first argument accepted by WriteLine() is the formatting string and the second and succeeding ones are the values to be used by the formatting string. If you look closely, the formatting string has {0}. They are called format placeholders. This will be substituted by the values of the next arguments. For example, the placeholder {0} means that it will be replaced by the value of the first argument following the formatting string. The new version of WriteLine method can actually accept any number of arguments, with the first one being the string containing the format placeholders, and the following arguments are the values that will substitute the format placeholders. For example, the following uses 4 placeholders.

Console.WriteLine("The values are {0}, {1}, {2}, and {3}.", value1, value2, value3, value4);

Format placeholders start with index 0. The number of placeholders must match the number of arguments following the formatting string. For example, if you have four placeholders as shown above, then you must provide four values right after the formatting string. The first placeholder {0} in the formatting string will be substituted by the second argument. The second placeholder {1} will be substituted by the third argument, and so on. It might be hard for beginners to understand this concept at first, but you will look at more examples of these in later lessons.