Variables
Variables are defined as a named memory location that can be assigned to a value. There are several types of variables, including the following:
- Local variables: These are variables that are defined within a method and their scope is local to that method.
- Method parameters: These are variables that hold the arguments passed to a method during a function call.
- Class fields: These are variables that are defined in the scope of the class and are accessible to all of the class methods and depending on the accessibility of the field to other classes too.
- Array elements: These are variables that refer to elements in an array.
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
.
Naming convention
There are several rules that must be followed for naming a variable:
- Variable names can consist of letters, digits, and underscore characters (
_
) only. - You cannot use any special character other than underscore (
_
) when naming a variable. Consequently, @sample, #tag, name%, and so on are illegal variable names. - The variable name must begin with a letter or an underscore character (
_
). The name of the variable cannot start with a digit. Therefore,2small
as a variable name will throw a compile-time error. - Variable names are case-sensitive. Therefore,
person
andPERSON
are considered two different variables. - A variable name cannot be any reserved keyword of C#. Hence
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. - Apart from the language rules that you must follow when naming variables, you should also make sure the names you choose are descriptive and easy to understand. You should always prefer that over short, abbreviated names that are hard to comprehend. There are various coding standards and naming conventions and you should adhere to one. These promote consistency and make the code easier to read, understand, and maintain.
When it comes to naming conventions, you should do the following when programming in C#:
- Use pascal case for classes, structures, enums, delegates, constructors, methods, properties, and constants. In Pascal case, each word in a name is capitalized; examples include
ConnectionString
,UserGroup
, andXmlReader
. - Use camel case for fields, local variables, and method parameters. In camel case, the first word of a name is not capitalized, but all of the others are; examples include
userId
,xmlDocument
, anduiControl
. - Do not use underscore in identifiers unless to prefix private fields, such as in
_firstName
, and_lastName
. - Prefer descriptive name over abbreviations. For example, prefer
labelText
overlbltxt
oremployeeId
overeid
.
You can learn more about coding standards and naming conventions in C# by consulting additional resources.
Implicity-typed variables
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:
- An implicitly typed variable must be initialized to a value at the time of declaration, otherwise, the compiler has no reference to infer the variable type and it results in a compile-time error.
- You cannot initialize it to null.
- The variable type cannot be changed once it is declared and initialized.
Information box
The
var
keyword is not a datatype but a placeholder for an actual type. Usingvar
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.
Understanding the scope and lifetime 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.