C# Variables
Introduction
Variables are fundamental building blocks in any programming language, including C#. They act as containers that store data in computer memory, allowing you to work with different types of information in your programs. In C#, variables are strongly typed, which means every variable must have a declared data type that determines what kind of data it can hold.
This guide will walk you through everything you need to know about C# variables, from basic declarations to best practices.
Variable Declaration and Initialization
Basic Syntax
In C#, you declare variables using the following syntax:
dataType variableName;
And initialize them like this:
dataType variableName = value;
Or you can separate declaration and initialization:
dataType variableName;
variableName = value;
Examples
Here's a simple example of declaring and initializing an integer variable:
int age = 25;
Console.WriteLine("Age: " + age);
// Output:
// Age: 25
You can also declare multiple variables of the same type in a single line:
int x = 10, y = 20, z = 30;
Console.WriteLine($"x: {x}, y: {y}, z: {z}");
// Output:
// x: 10, y: 20, z: 30
C# Data Types
C# offers various built-in data types to handle different kinds of information. Here are the most common ones:
Value Types
Data Type | Description | Range | Example |
---|---|---|---|
int | 32-bit signed integer | -2,147,483,648 to 2,147,483,647 | int count = 42; |
float | 32-bit floating-point | ±1.5 × 10^-45 to ±3.4 × 10^38 | float price = 19.99f; |
double | 64-bit floating-point | ±5.0 × 10^-324 to ±1.7 × 10^308 | double distance = 456.789; |
decimal | 128-bit precise decimal | ±1.0 × 10^-28 to ±7.9 × 10^28 | decimal money = 125.45m; |
char | Single 16-bit Unicode character | U+0000 to U+FFFF | char grade = 'A'; |
bool | Boolean value | true or false | bool isActive = true; |
Reference Types
Data Type | Description | Example |
---|---|---|
string | Sequence of characters | string name = "John Doe"; |
object | Base type of all types | object data = 42; |
Arrays | Collection of values | int[] numbers = {1, 2, 3}; |
Classes | User-defined types | Person person = new Person(); |
Example with Different Types
// Value types
int age = 30;
double height = 5.9;
bool isEmployed = true;
char grade = 'A';
decimal salary = 5000.50m;
// Reference types
string name = "Alice Johnson";
int[] scores = { 85, 90, 78, 92, 88 };
Console.WriteLine($"Name: {name}, Age: {age}");
Console.WriteLine($"Height: {height}ft, Grade: {grade}");
Console.WriteLine($"Is employed? {isEmployed}");
Console.WriteLine($"Salary: ${salary}");
Console.WriteLine("Scores: " + string.Join(", ", scores));
// Output:
// Name: Alice Johnson, Age: 30
// Height: 5.9ft, Grade: A
// Is employed? True
// Salary: $5000.50
// Scores: 85, 90, 78, 92, 88
Type Inference with var
C# allows you to use the var
keyword for implicit typing, where the compiler determines the variable's type based on the assigned value.
var message = "Hello, World!"; // Compiler infers it as string
var number = 42; // Compiler infers it as int
var pi = 3.14159; // Compiler infers it as double
Console.WriteLine($"{message} The answer is {number} and PI is {pi}");
// Output:
// Hello, World! The answer is 42 and PI is 3.14159
Important: When using var
:
- You must initialize the variable at declaration
- The type is determined at compile-time, not runtime
- It doesn't make the variable loosely typed
Constants
When you have values that should never change during program execution, you can use constants:
const double Pi = 3.14159;
const string AppName = "My C# Application";
// Attempting to modify a constant will result in a compilation error
// Pi = 3.14; // This would cause an error
Console.WriteLine($"Application: {AppName}");
Console.WriteLine($"Pi value: {Pi}");
// Output:
// Application: My C# Application
// Pi value: 3.14159
Variable Scope
The scope of a variable defines where in the code you can access that variable. C# has several scope levels:
Block Scope
Variables declared within a code block (enclosed by {}
) are only accessible within that block.
{
int blockVariable = 100;
Console.WriteLine($"Inside block: {blockVariable}");
}
// Console.WriteLine(blockVariable); // Error: blockVariable doesn't exist here
Method Scope
Variables declared in a method are accessible only within that method.
void ExampleMethod()
{
int methodVariable = 200;
Console.WriteLine($"Inside method: {methodVariable}");
}
// methodVariable is not accessible outside the method
Class Scope (Fields)
Variables declared at the class level (fields) are accessible throughout the class.
class Person
{
// Class-level variable (field)
private string name = "John";
public void PrintName()
{
Console.WriteLine(name); // name is accessible here
}
public void ChangeName(string newName)
{
name = newName; // Can modify the field
}
}
Practical Examples
Example 1: Temperature Converter
// Temperature converter using variables
Console.Write("Enter temperature in Celsius: ");
double celsius = Convert.ToDouble(Console.ReadLine());
double fahrenheit = (celsius * 9 / 5) + 32;
Console.WriteLine($"{celsius}°C = {fahrenheit}°F");
// Example output with input "25":
// Enter temperature in Celsius: 25
// 25°C = 77°F
Example 2: Simple Interest Calculator
// Simple interest calculator
decimal principal = 1000m;
decimal rate = 0.05m; // 5% annual interest
int time = 2; // 2 years
decimal interest = principal * rate * time;
decimal amount = principal + interest;
Console.WriteLine($"Principal: ${principal}");
Console.WriteLine($"Interest Rate: {rate * 100}%");
Console.WriteLine($"Time Period: {time} years");
Console.WriteLine($"Simple Interest: ${interest}");
Console.WriteLine($"Total Amount: ${amount}");
// Output:
// Principal: $1000
// Interest Rate: 5%
// Time Period: 2 years
// Simple Interest: $100
// Total Amount: $1100
Example 3: User Information Program
// Program to collect and display user information
Console.Write("Enter your name: ");
string userName = Console.ReadLine();
Console.Write("Enter your age: ");
int userAge = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter your height (in meters): ");
double userHeight = Convert.ToDouble(Console.ReadLine());
bool isAdult = userAge >= 18;
Console.WriteLine("\nUser Information:");
Console.WriteLine($"Name: {userName}");
Console.WriteLine($"Age: {userAge}");
Console.WriteLine($"Height: {userHeight}m");
Console.WriteLine($"Is adult: {isAdult}");
Console.WriteLine($"Birth year (approx.): {DateTime.Now.Year - userAge}");
// Example output with inputs "Sarah", "22", "1.65":
// Enter your name: Sarah
// Enter your age: 22
// Enter your height (in meters): 1.65
//
// User Information:
// Name: Sarah
// Age: 22
// Height: 1.65m
// Is adult: True
// Birth year (approx.): 2001
Best Practices
-
Use Meaningful Names: Choose descriptive names for variables that explain what they represent.
csharp// Poor naming
int x = 86400;
// Better naming
int secondsInDay = 86400; -
Follow Naming Conventions:
- Use camelCase for local variables and parameters (
firstName
) - Use PascalCase for constants (
MaxValue
) - Avoid using reserved keywords as variable names
- Use camelCase for local variables and parameters (
-
Initialize Variables: Always initialize variables before using them to avoid unexpected behaviors.
-
Limit Variable Scope: Declare variables in the narrowest scope possible.
-
Use Constants: For values that shouldn't change during runtime.
-
Choose the Right Type: Select the most appropriate data type for your needs to optimize memory usage.
Summary
In this guide, you've learned about:
- How to declare and initialize variables in C#
- Different data types available in C# (value types and reference types)
- Type inference using the
var
keyword - How to use constants
- Understanding variable scope
- Practical examples showing variables in action
Variables are the building blocks of any C# program, allowing you to store, manipulate, and work with data. Mastering variables and their types is essential for effective C# programming, as they form the foundation upon which more complex concepts are built.
Exercises
- Create a program that calculates the area and perimeter of a rectangle using variables.
- Write a program that converts a given number of days into years, months, and days.
- Create a simple console-based calculator that takes two numbers and performs basic arithmetic operations.
- Write a program that swaps the values of two variables without using a third variable.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)