Skip to main content

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:

csharp
dataType variableName;

And initialize them like this:

csharp
dataType variableName = value;

Or you can separate declaration and initialization:

csharp
dataType variableName;
variableName = value;

Examples

Here's a simple example of declaring and initializing an integer variable:

csharp
int age = 25;
Console.WriteLine("Age: " + age);

// Output:
// Age: 25

You can also declare multiple variables of the same type in a single line:

csharp
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 TypeDescriptionRangeExample
int32-bit signed integer-2,147,483,648 to 2,147,483,647int count = 42;
float32-bit floating-point±1.5 × 10^-45 to ±3.4 × 10^38float price = 19.99f;
double64-bit floating-point±5.0 × 10^-324 to ±1.7 × 10^308double distance = 456.789;
decimal128-bit precise decimal±1.0 × 10^-28 to ±7.9 × 10^28decimal money = 125.45m;
charSingle 16-bit Unicode characterU+0000 to U+FFFFchar grade = 'A';
boolBoolean valuetrue or falsebool isActive = true;

Reference Types

Data TypeDescriptionExample
stringSequence of charactersstring name = "John Doe";
objectBase type of all typesobject data = 42;
ArraysCollection of valuesint[] numbers = {1, 2, 3};
ClassesUser-defined typesPerson person = new Person();

Example with Different Types

csharp
// 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.

csharp
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:

csharp
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.

csharp
{
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.

csharp
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.

csharp
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

csharp
// 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

csharp
// 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

csharp
// 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

  1. Use Meaningful Names: Choose descriptive names for variables that explain what they represent.

    csharp
    // Poor naming
    int x = 86400;

    // Better naming
    int secondsInDay = 86400;
  2. Follow Naming Conventions:

    • Use camelCase for local variables and parameters (firstName)
    • Use PascalCase for constants (MaxValue)
    • Avoid using reserved keywords as variable names
  3. Initialize Variables: Always initialize variables before using them to avoid unexpected behaviors.

  4. Limit Variable Scope: Declare variables in the narrowest scope possible.

  5. Use Constants: For values that shouldn't change during runtime.

  6. 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

  1. Create a program that calculates the area and perimeter of a rectangle using variables.
  2. Write a program that converts a given number of days into years, months, and days.
  3. Create a simple console-based calculator that takes two numbers and performs basic arithmetic operations.
  4. 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! :)