II.5. Variable Rules
In C#, variable names must adhere to the following rules:
- The name can contain letters, digits, and the underscore character (_).
- The first character of the name must be a letter. ...
- Case matters (that is, upper- and lowercase letters). ...
- C# keywords can't be used as variable names.
II.6. Scope of Variable
The part of the program where a particular variable is accessible is termed as the Scope of that variable. A variable can be defined in a class, method, loop etc. In C/C++, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of the function call stack. But the C# programs are organized in the form of classes.
So C# scope rules of variables can be divided into three categories as follows:
- Class Level Scope
- Method Level Scope
- Block Level Scope
1. Local Variable
A local variable, in C#, is a type of variable declared by local variable declaration at the beginning of a block the variable is intended to be local to. It can also occur in a for-statement, a switch-statement, a foreach statement, a using statement or a specific-catch statement or using statement.
- Ex:
2.Global Variable
What is a "Global" Variable?
A global variable is a variable accessible anywhere, for example a field "counter" type integer.
The global variable can be accessed from any function or class within the namespace.
Ex:
public class Globals
{
private static bool _expired;
public static bool Expired
{
get
{
// Reads are usually simple
return _expired;
}
set
{
// You can add logic here for race conditions,
// or other measurements
_expired = value;
}
}
// Perhaps extend this to have Read-Modify-Write static methods
// for data integrity during concurrency? Situational.
}
II. Constants
What is a Constant variable?
A variable whose value can not be changed during the execution of the program is called a constant variable.
In the above definition, the value can not be changed during execution of the program, which means we cannot assign values to the constant variable at run time. Instead, it must be assigned at the compile time.
In the above diagram, we can see the Constants are of two types
- Compile time constants (const)
- Runtime constants (Readonly)
Compile time constants
The compile time constants are declared by using the const keyword, in which the value can not be changed during the execution of the program.
0 Comments