Variables in .NET
Variables are fundamental to programming. They are named storage locations that hold values. In .NET, you declare a variable by specifying its type and a name, and optionally initializing it with a value.
Declaring and Initializing Variables
The basic syntax for declaring a variable is:
<data_type> <variable_name>;
And to initialize it:
<data_type> <variable_name> = <value>;
Example: Declaring and Initializing Integers
Here's how you declare and initialize integer variables:
int age;
age = 30;
string name = "Alice";
double price = 19.99;
bool isStudent = true;
Variable Naming Rules
- Variable names must start with a letter or an underscore (_).
- They cannot start with a number.
- They can contain letters, numbers, and the underscore character.
- Variable names are case-sensitive (e.g.,
myVariable
is different frommyvariable
). - They cannot be C# keywords (like
int
,string
,if
, etc.). - It's a common convention to use camelCase for local variables (e.g.,
userName
) and PascalCase for class members and public properties.
Implicitly Typed Local Variables (var
)
C# also supports implicitly typed local variables using the var
keyword. The compiler infers the data type from the initialization value.
var count = 100; // Compiler infers 'int'
var message = "Hello, World!"; // Compiler infers 'string'
var pi = 3.14159; // Compiler infers 'double'
The var
keyword can only be used for local variables. The type is determined at compile time, not runtime.
Variable Scope
The scope of a variable refers to the region of your code where it is accessible. Variables declared within a block of code (e.g., inside a method or a loop) are only accessible within that block.
public void MyMethod()
{
int localVar = 10; // localVar is only accessible within MyMethod
if (localVar > 5)
{
int anotherVar = 20; // anotherVar is only accessible within this if block
Console.WriteLine(localVar);
Console.WriteLine(anotherVar);
}
// Console.WriteLine(anotherVar); // This would cause a compile-time error
}