-
Book Overview & Buying
-
Table Of Contents
Learn C# Programming
By :
Variables are defined as a named memory location that can be assigned to a value. There are several types of variables, including the following:
In this section, we will refer to local variables, which are variables declared in the body of a function. Such variables are declared using the following syntax:
datatype variable_name;
In this statement, datatype is the data type of the variable and variable_name is the name of the variable. Here are several examples:
bool f; char ch = 'x'; int a, b = 20, c = 42; a = -1; f = true;
In this example, f is an uninitialized bool variable. Uninitialized variables cannot be used in any expression. An attempt to do so will result in a compiler error. All variables must be initialized before they are used. A variable can be initialized when declared, such as with ch, b, and c in the preceding example, or at any later time, such as with a and f.
Multiple variables of the same type can be declared and initialized in a single statement, separated by a comma. This is exemplified in the preceding code snippet with the int variables a, b, and c.
There are several rules that must be followed for naming a variable:
_) only._) when naming a variable. Consequently, @sample, #tag, name%, and so on are illegal variable names._). The name of the variable cannot start with a digit. Therefore, 2small as a variable name will throw a compile-time error.person and PERSON are considered two different variables.true, false, double, float, var, and so on are illegal variable names. However, prefixing a keyword with @ enables the compiler to treat them as identifiers, rather than keywords. Therefore, variables names such as @true, @return, @var are allowed. These are called verbatim identifiers.When it comes to naming conventions, you should do the following when programming in C#:
ConnectionString, UserGroup, and XmlReader.userId, xmlDocument, and uiControl._firstName, and_lastName.labelText over lbltxt or employeeId over eid.You can learn more about coding standards and naming conventions in C# by consulting additional resources.
As we have seen in previous examples, we need to specify the type of a variable when we are declaring it. However, C# provides us with another way to declare variables that allows the compiler to infer the variable type based on the value assigned to it during initialization. These are known as implicitly typed variables.
We can create an implicitly typed variable using the var keyword. Such variables must always be initialized on the declaration because the compiler infers the type of the variable from the value that it is initialized with. Here is an example:
var a = 10;
Since the a variable is initialized with an integer literal, a is considered as an int variable by the compiler.
When declaring variables with var, you must keep in mind the following:
Information box
The var keyword is not a datatype but a placeholder for an actual type. Using var to declare variables is useful when the type name is long and you want to avoid typing a lot (for example, Dictionary<string, KeyValuePair<int, string>>) or you do not care about the actual type, only the value.
Now that you learned how you can declare variables, let's look at a key concept: the scope of variables.
A scope in C# is defined as a block between an opening curly brace and its corresponding closing curly brace. The scope defines the visibility and lifetime of a variable. A variable can be accessed only within the scope in which it is defined. A variable that is defined in a particular scope is not visible to the code outside that scope.
Let's understand this with the help of an example:
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 10; i++)
{
Console.WriteLine(i);
}
i = 20; // i is out of scope
}
}
In this example, the i variable is defined inside the for loop, hence it cannot be accessed outside the for loop as it goes out of scope once the control exits the loop. You will learn more about the for loop in the next chapter.
We can also have nested scopes. This means a variable defined in a scope can be accessed in another scope that is enclosed in that scope. However, the variables from the outer scope are visible to the inner scope but the inner scope variables are not accessible in the outer scope. The C# compiler won't allow you to create two variables with the same name within a scope.
Let's extend the code in the previous example to understand this:
class Program
{
static void Main(string[] args)
{
int a = 5;
for (int i = 1; i < 10; i++)
{
char a = 'w'; // compiler error
if (i % 2 == 0)
{
Console.WriteLine(i + a); // a is within the
// scope of Main
}
}
i = 20; // i is out of scope
}
}
Here, the integer variable a is defined outside the for loop but within the scope of Main. Hence, it can be accessed within the for loop as it is in the scope of this. However, the i variable, which is defined inside the for loop, cannot be accessed inside the scope of Main.
If we try to declare another variable with the same name in the scope, we will get a compile-time error. Consequently, we cannot declare a character variable a inside the for loop as we already have an integer variable with the same name.