A variable in C# is a storage location in the computer’s memory that is used to hold data. Each variable has:
- A name to identify it (like a label on the storage).
- A data type to specify the kind of data it can hold (like numbers, text, etc.).
- A value which is the data the variable holds (like 10, “Hello”, true, etc.).
Syntax:
dataType variable_name = variable_value;
Example:
string a = "Hello World";
Rules for declare Naming Variables
1. It must start with a letter (a-z, A-Z) or an underscore (_).
2. Subsequent characters can include letters, digits (0-9), or underscores.
3. It can not start with a digit.
4. It can not be a C# keyword (e.g., int, class, bool).
5. Variable names are case-sensitive.
Example of Valid Variable
string name;
bool isAdmin;
Example of Invalid Variable
string class;
Declaring and Initializing Variables
1. Declaration: Telling the program about the variable’s type and name.
2. Initialization: Giving the variable a value
1. You can declare and initialize a variable in a single step:
Example:
int age = 35;
2. declare and initialize separately
int age; // Declaration
age = 35; // Initialization
Default Values of Variables
If you declare a variable without giving it a value, C# assigns a default value depending on the type.
- int gets 0
- bool gets false.
- string gets null (because it’s an object type).
- double gets 0.0.