The Variables - C# Programming Bootcamp: Learn the Basics of C# Programming in 2 Weeks (2016)

C# Programming Bootcamp: Learn the Basics of C# Programming in 2 Weeks (2016)

Chapter 5. The Variables

The term variable refers to memory locations that can be manipulated by computer programs. Every variable in this programming language belongs to a certain type, which specifies the following aspects:

· The size and structure of the memory used by the variable

· The values that you can store inside the variable’s memory

· The group of operations that you can apply to the variable.

You can categorize the value types in C# this way:

1. The Decimal Types

2. The Nullable Types

3. The Integral Types

4. The Boolean Types

5. The Floating Point Types

How to Define a Variable

When defining a variable, use the following syntax:

In this syntax, you must replace“data_type” with a data type in the C# language. For“variable_list,” you may add one or more identifiers. You should separate identifiers using commas.

How to Initialize a Variable

You can initialize variables using“=” (i.e. the equal sign). To complete the process, just add a constant expression after the equal sign. Here’s the basic syntax of variable initialization:

You may initialize variables during the declaration phase. As discussed above, initialization is achieved by placing“=” followed by an expression. Here’s an example:

To help you understand this concept, more examples are given below:

int x = 2, y = 3; /* it initializes x and y */

byte d = 99; /* it initializes d */

char a =‘a’; /* the variable named a has‘a’ as its value */

According to expert programmers, you should always initialize variables correctly. If you won’t, your programs may behave unexpectedly or produce undesirable results.

How to Enter a Value

C# has a namespace called System. This namespace contains different classes, one of which is Console. This class offers ReadLine(), a function that accepts inputs from the users and stores them into variables.

For instance:

Console.ReadLine() receives data as string variables. If you prefer to use the data as int variables, you may use a function called Convert.ToInt32().


The Rvalue and Lvalue Expressions

The C# programming language supports two types of expressions:

1. rvalue– This kind of expression may appear on the right side, but never on the left side, of any assignment.

2. lvalue– This kind of expression may appear on the right side or left side of any assignment.

Variables are classified as lvalues. Thus, they can appear on either side of your assignments. The numeric literals, on the other hand, are classified as rvalues. That means you can’t assign them nor place them on the left side of your assignments. Check the two examples below:

· Valid Statement for C#: int x = 99

· Invalid Statement for C#: 99 = 66