In C#, a variable is a named storage location in memory that holds a value of a specific data type. Variables allow programs to store, modify, and retrieve data dynamically.
To declare a variable, specify the data type followed by the variable name:
int age; // Declares an integer variable
string name; // Declares a string variable
bool isActive; // Declares a boolean variable
Variables can be assigned a value at the time of declaration or later:
int age = 25; // Initialization during declaration
string name = "LoopCode"; // Initialization
bool isActive = true;
In C#, variables can be categorized based on their scope and lifetime:
void Demo() {
int localVar = 10; // local variable
Console.WriteLine(localVar);
}
class Person {
public string name; // instance variable
}
Person p = new Person();
p.name = "Rahul";
static keyword. Shared among all objects of the class.
class Counter {
public static int count = 0; // static variable
}
Counter.count++;
readonly. Value assigned once and cannot be changed.
readonly int maxValue = 100;
const. Value cannot be changed after declaration.
const double PI = 3.14159;
Keywords are reserved words that have a special meaning in C#. They cannot be used as variable names.
// Valid variable names
int age = 25;
string firstName = "Rahul";
bool isActive = true;
// Using var keyword
var number = 100; // Compiler infers type int
var text = "Hello"; // Compiler infers type string
Console.WriteLine(age);
Console.WriteLine(firstName);
Console.WriteLine(isActive);
Console.WriteLine(number);
Console.WriteLine(text);
Variables and keywords form the foundation of C# programming. Understanding how to declare, initialize, and use them correctly is essential for writing readable and maintainable code.