C# Variables
What is a Variable?
In C#, a variable is a container for storing data values. Variables serve as named memory locations where data can be stored and manipulated during program execution. Each variable has a specific data type that determines what kind of information it can hold.
Basic Variable Declaration:
// Type variableName = value;
int myNum = 5; // Integer (whole number)
double myDoubleNum = 5.99D; // Floating point number
char myLetter = 'D'; // Character
bool myBool = true; // Boolean
string myText = "Hello"; // String
Variable Naming Rules
When naming variables in C#, you must follow these rules:
- Must start with a letter or underscore (_)
- Cannot start with a number
- Cannot contain spaces or special characters like !, @, #, etc.
- Cannot be a C# keyword (like int, string, class, etc.)
- Are case-sensitive (age and Age are different variables)
Valid and Invalid Variable Names:
// Valid variable names
int age;
string userName;
double _temperature;
bool isActive;
int totalItems123;
// Invalid variable names
// int 1stNumber; // Cannot start with a number
// string user-name; // Cannot contain hyphen
// double class; // Cannot use C# keywords
// bool my variable; // Cannot contain spaces
C# Naming Conventions
While not required by the compiler, following these conventions makes your code more readable and maintainable:
- camelCase for local variables and method parameters (e.g.,
firstName,totalAmount) - PascalCase for class names, method names, and properties (e.g.,
Customer,CalculateTotal) - _camelCase for private fields (e.g.,
_firstName) - ALL_UPPERCASE for constants (e.g.,
MAX_SIZE,PI)
Variable Declaration and Initialization
In C#, you have several ways to declare and initialize variables:
// Declaration without initialization (default values are assigned)
int count; // Default value: 0
bool flag; // Default value: false
string name; // Default value: null
// Declaration with initialization
int age = 25;
string firstName = "John";
// Multiple declarations of the same type
int x = 10, y = 20, z = 30;
// Using var (type inference) - compiler determines the type based on the value
var total = 100; // Inferred as int
var message = "Hello"; // Inferred as string
var price = 29.99; // Inferred as double
var today = DateTime.Now; // Inferred as DateTime
Note on var:
When using var, the variable must be initialized at the time of declaration, as the compiler needs the initial value to determine the type. Once the type is inferred, it cannot be changed later.
Getting User Input for Variables
In console applications, you can use Console.ReadLine() to get user input and assign it to variables:
// Reading string input
Console.Write("Enter your name: ");
string name = Console.ReadLine(); // ReadLine returns a string
// Converting string input to numeric types
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = Convert.ToInt32(ageInput); // Convert string to int
// Alternative conversion methods
Console.Write("Enter your height in meters: ");
double height = double.Parse(Console.ReadLine()); // Using parse method
// Safe conversion with TryParse
Console.Write("Enter number of items: ");
string itemsInput = Console.ReadLine();
if (int.TryParse(itemsInput, out int items))
{
Console.WriteLine($"You entered {items} items");
}
else
{
Console.WriteLine("That's not a valid number");
}
// Reading multiple inputs
Console.Write("Enter first name and last name separated by space: ");
string fullNameInput = Console.ReadLine();
string[] nameParts = fullNameInput.Split(' ');
string firstName = nameParts[0];
string lastName = nameParts[1];
Console.WriteLine($"First name: {firstName}, Last name: {lastName}");
Important Notes on User Input:
Console.ReadLine()always returns a string, regardless of what the user types- To use numeric input, you must convert the string to the appropriate type
- Always validate user input to handle invalid entries, especially when converting to numeric types
- Use
TryParsemethods for safer conversion that won't crash on invalid input
Variable Scope
The scope of a variable determines where in the code the variable is accessible. C# has several levels of scope:
Block Scope:
void ExampleMethod()
{
// Method-level scope
int outerVariable = 10;
if (outerVariable > 5)
{
// Block-level scope
int innerVariable = 20;
Console.WriteLine(outerVariable); // Can access outerVariable
Console.WriteLine(innerVariable); // Can access innerVariable
}
Console.WriteLine(outerVariable); // Can access outerVariable
// Console.WriteLine(innerVariable); // ERROR: Cannot access innerVariable here
}
Class Scope:
class Person
{
// Class-level fields (accessible throughout the class)
private string _name;
private int _age;
// Constructor
public Person(string name, int age)
{
// Constructor parameters (method scope)
_name = name; // Assign parameter to field
_age = age; // Assign parameter to field
}
public void DisplayInfo()
{
// Local variable (method scope)
string message = $"Name: {_name}, Age: {_age}";
Console.WriteLine(message);
}
}
Constants
Constants are values that cannot be modified after they are declared. They must be initialized at the time of declaration:
// Constants must be assigned a value when declared
const double PI = 3.14159;
const int MAX_USERS = 100;
const string CONNECTION_STRING = "Server=myServerAddress;Database=myDataBase;";
// This will cause a compilation error:
// PI = 3.14; // Constants cannot be changed
When to Use Constants:
Use constants for values that are truly fixed and will never change, such as mathematical constants, fixed configuration values, or fixed business rules. Constants are evaluated at compile time, so they're very efficient.
Read-only Fields
For class-level variables that should be immutable but can be set at runtime (usually in a constructor), use the readonly keyword:
public class Configuration
{
// Read-only fields - can only be assigned in declaration or constructor
private readonly string _serverName;
private readonly int _timeoutSeconds;
public readonly DateTime CreationTime = DateTime.Now;
public Configuration(string serverName)
{
_serverName = serverName;
_timeoutSeconds = 30; // Can set in constructor
}
public void ChangeSettings()
{
// This would cause a compilation error:
// _serverName = "newServer"; // Cannot modify readonly fields
}
}
Working with Variables
Once declared, variables can be manipulated in various ways:
Variable Operations:
// Arithmetic operations
int a = 10;
int b = 3;
int sum = a + b; // Addition: 13
int difference = a - b; // Subtraction: 7
int product = a * b; // Multiplication: 30
int quotient = a / b; // Division: 3 (integer division)
int remainder = a % b; // Modulus (remainder): 1
// Compound assignment operators
int count = 5;
count += 2; // Equivalent to: count = count + 2; (count becomes 7)
count -= 1; // Equivalent to: count = count - 1; (count becomes 6)
count *= 3; // Equivalent to: count = count * 3; (count becomes 18)
count /= 2; // Equivalent to: count = count / 2; (count becomes 9)
// Increment and decrement
int x = 10;
x++; // Increment by 1 (x becomes 11)
x--; // Decrement by 1 (x becomes 10)
// Pre-increment and post-increment
int y = 5;
int z1 = ++y; // Pre-increment: y becomes 6, then z1 is assigned 6
int z2 = y++; // Post-increment: z2 is assigned 6, then y becomes 7
Displaying Variables
There are multiple ways to display variables in C#:
Output Methods:
// String concatenation (using + operator)
string name = "Alice";
int age = 28;
Console.WriteLine("Name: " + name + ", Age: " + age);
// String interpolation (recommended, C# 6.0+)
Console.WriteLine($"Name: {name}, Age: {age}");
// String.Format method
Console.WriteLine(String.Format("Name: {0}, Age: {1}", name, age));
// Composite formatting
Console.WriteLine("Name: {0}, Age: {1}", name, age);
// With formatting options
double price = 123.45;
Console.WriteLine($"Price: {price:C}"); // Currency format: $123.45 (locale-dependent)
Console.WriteLine($"Price: {price:F1}"); // Fixed-point: 123.5 (1 decimal place)
Console.WriteLine($"Tax rate: {0.0825:P}"); // Percentage: 8.25%
Common Pitfalls
- Uninitialized Variables - Local variables must be initialized before use
- Variable Shadowing - Declaring a variable inside a block with the same name as a variable in an outer block
- Confusing Value vs. Reference Types - Understanding how variables store data (by value or by reference)
- Var Misuse - Using var excessively can make code harder to understand
Variable Shadowing Example:
int x = 10; // Outer variable
if (true)
{
int x = 20; // Inner variable (shadows the outer one)
Console.WriteLine(x); // Outputs: 20 (refers to the inner variable)
}
Console.WriteLine(x); // Outputs: 10 (refers to the outer variable)
Practice with Variables
To practice using variables, try the Beginner C# Course which includes hands-on exercises where you can write and run code.
Test Your Knowledge: Variables
Question 1: Which of the following correctly declares an integer variable named 'count' with a value of 10?
Question 2: What will be the output of the following code?
int x = 5;
int y = 2;
int z = x + y;
Console.WriteLine(z);
Question 3: Which statement about the const keyword is true?