In C#, a variable is a storage location in memory that holds data. Variables have a name, type, and value, and they are used to store and manipulate information in a program.
This tutorial will cover:
- Declaring and Initializing Variables
- Data Types in C#
- Rules for Naming Variables
- Variable Scope
- Constants and Readonly Variables
- Type Inference with var
- Nullable Variables
- Best Practices for Using Variables
1. Declaring and Initializing Variables
In C#, a variable is declared by specifying a data type followed by a variable name.
Syntax:
dataType variableName;
Example: Declaring a Variable
int age; // Declares a variable named 'age' of type integer
Example: Declaring and Initializing a Variable
int age = 25; // Declares and assigns a value
Multiple variables of the same type can be declared in a single line:
int x = 10, y = 20, z = 30;
2. Data Types in C#
C# has different types of variables classified into value types and reference types.
Common Data Types in C#
Data Type | Size | Example | Description |
---|---|---|---|
int | 4 bytes | int age = 25; | Stores whole numbers |
double | 8 bytes | double pi = 3.14; | Stores decimal numbers |
char | 2 bytes | char letter = ‘A’; | Stores a single character |
string | Variable | string name = “John”; | Stores a sequence of characters |
bool | 1 byte | bool isActive = true; | Stores true or false |
decimal | 16 bytes | decimal price = 99.99m; | Stores high-precision decimals |
float | 4 bytes | float rate = 5.5f; | Stores floating-point numbers |
long | 8 bytes | long population = 8000000000; | Stores large whole numbers |
3. Rules for Naming Variables
Variable names in C# must follow certain rules:
Valid Naming Rules
- Variable names must start with a letter (A-Z or a-z) or an underscore (_).
- Cannot contain spaces or special characters except _.
- Cannot be a C# keyword like int, class, public, etc.
- Should follow camelCase convention (studentName, totalAmount).
Valid Examples
int studentAge; string firstName; double _accountBalance;
Invalid Examples
int 1number; // Invalid: Cannot start with a number string first name; // Invalid: Cannot contain spaces double float; // Invalid: 'float' is a keyword
4. Variable Scope
A variable’s scope defines where it can be accessed. C# has three types of scope:
Local Variables (Inside Methods)
Declared inside a method and cannot be accessed outside.
void DisplayMessage() { string message = "Hello"; // Local variable Console.WriteLine(message); }
Instance Variables (Inside a Class)
Declared inside a class but outside methods. Can be accessed anywhere inside the class.
class Person { string name = "John"; // Instance variable }
Static Variables (Shared Across Instances)
Declared using static keyword. Shared across all instances of the class.
class Example { static int count = 0; // Static variable }
5. Constants and Readonly Variables
Constants (const)
A const variable must be assigned at declaration and cannot be changed later.
const double Pi = 3.14159;
Readonly Variables (readonly)
A readonly variable can be assigned only in the constructor.
class Example { readonly int number; public Example(int num) { number = num; // Allowed inside constructor } }
6. Type Inference with var
The var keyword allows automatic type inference based on assigned value.
Example: Using var
var age = 30; // Compiler infers 'int' var price = 19.99; // Compiler infers 'double'
Rules for var:
- Cannot be null unless nullable.
- Must be initialized at declaration.
- Improves code readability but should be used carefully.
7. Nullable Variables
C# allows nullable types using ?.
Example: Nullable Variables
int? number = null; // Can hold either an integer or null
Checking for Null Values
if (number.HasValue) { Console.WriteLine(number.Value); } else { Console.WriteLine("No value assigned"); }
Null Coalescing Operator (??)
If number is null, it assigns a default value.
int value = number ?? 100; // If 'number' is null, assign 100
8. Best Practices for Using Variables
Use meaningful names
int customerAge; // Good int x; // Bad
Use camelCase for local variables
string firstName; double accountBalance;
Use PascalCase for Constants
const double Pi = 3.14159;
Prefer var only when necessary
var userAge = 25; // Acceptable
Use const and readonly for fixed values
const double TaxRate = 0.18; readonly string CompanyName = "Tech Corp";
Conclusion
- Variables store data and are defined by a type, name, and value.
- Scope determines where a variable is accessible.
- Constants (const) and readonly variables are used for fixed values.
- var allows type inference, but it should be used wisely.
- Nullable types (int?) handle missing values.