New Batch Starts 1st September 2025 – Join Our .NET Full Stack Development Course, Daily 6-8 AM and 8.30-10.30 PM, Register Now
+91 9989950088
info@example.com
Variables in C#

📝 What is a Variable?


A variable is a named storage location in memory that holds a value. The value can be changed while the program runs. Think of a variable as a labeled box where you can store information to use later.

In C#, variables make programs dynamic, readable, and maintainable. Since C# is a strongly typed language, every variable must have a data type that defines the kind of data it can hold.

Types of Variables
  • Value Types: Store actual data. Examples: int, double, float, char, bool.
    Example: int age = 25;, bool isActive = true;
  • Reference Types: Store memory address of the data. Examples: string, object, arrays.
    Example: string name = "Megha";
  • Implicitly Typed: Use var, compiler determines type automatically.
    Example: var total = 100;

✅ Using variables efficiently helps in writing clean, dynamic, and error-free C# programs.

💡 Importance of Variables in C#

, po;.jl.

Variables are the backbone of any program. They allow you to store and manipulate data efficiently, making your code dynamic, readable, and maintainable. fnnvg

Key Reasons to Use Variables:
  • 🔹 Temporary Data Storage: Keep values during program execution without hardcoding.
  • 🔹 Efficient Data Manipulation: Easily update or process data throughout the program.
  • 🔹 Readable & Maintainable Code: Makes it easier for developers to understand and modify code.
  • 🔹 Dynamic Calculations: Perform calculations or operations without rewriting values.

🗂️ Types of Variables


C# is a strongly typed language, which means every variable must have a data type. Variables can be categorized as:

1️⃣ Value Types

These store actual data directly in memory.

Data Type Size Example
int 4 bytes int age = 25;
double 8 bytes double price = 199.99;
float 4 bytes float temp = 36.6f;
char 2 bytes char grade = 'A';
bool 1 byte bool isValid = true;
2️⃣ Reference Types

These store the memory address of the data, not the actual data itself.

Data Type Example
string string name = "Megha";
object object obj = new object();
arrays int[] numbers = {1,2,3};
3️⃣ Implicitly Typed Variables

C# can infer the type automatically using var.

  • var number = 100; // Compiler infers int
  • var name = "Megha"; // Compiler infers string

📝 Declaration & Initialization


1️⃣ Declaration

Declaration tells the compiler that a variable exists.

int age; // declaration
2️⃣ Initialization

Initialization assigns a value to the variable.

age = 25; // initialization
3️⃣ Declaration & Initialization Together

You can declare and initialize a variable at the same time.

int age = 25;
string name = "Megha";

🖊️ Rules for Naming Variables


In C#, variable names must follow certain rules to avoid errors and maintain readable code. Here are the key rules:

  • ✅ Names must start with a letter or underscore (_).
  • ✅ Names can contain letters, digits, and underscores, but no spaces or special characters.
  • ✅ Variable names cannot be C# reserved keywords (like int, class, for).
  • ✅ Names are case-sensitive (age and Age are different).
  • ✅ Names should be meaningful and descriptive (age instead of a).
  • ✅ Avoid starting names with digits (1stNumber is invalid).
Examples:
int age = 25;
string firstName = "Megha";
double _price = 199.99;

🎯 Default Values


In C#, variables have default values depending on their type if they are declared as **class-level members** but not explicitly initialized.

Data Type Default Value
int 0
double 0.0
float 0.0f
char '\0' (null character)
bool false
string null
object null

⚖️ Advantages & Disadvantages of Variables


✅ Advantages
  • Easy to store, retrieve, and manipulate data dynamically.
  • Improves code readability and maintainability.
  • Reduces redundancy by avoiding hardcoded values.
  • Supports dynamic calculations and program logic.
  • Makes programs scalable and less error-prone.
❌ Disadvantages
  • Excessive or unnecessary variables can consume memory.
  • Incorrectly typed variables may cause runtime errors.
  • Poor naming conventions reduce code readability.
  • Overusing global variables can make debugging difficult.
C# Variables Example (Value & Reference Types)

Program: VariableDemo.cs


using System;

namespace VariableExample
{
    class Program
    {
        static void Main()
        {
            // Value Types
            int age = 21;
            double price = 199.99;
            bool isStudent = true;

            // Reference Types
            string name = "Megha";
            int[] numbers = { 1, 2, 3, 4, 5 };

            // Output
            Console.WriteLine("Value Types:");
            Console.WriteLine("Age: " + age);
            Console.WriteLine("Price: " + price);
            Console.WriteLine("Is Student? " + isStudent);

            Console.WriteLine("\nReference Types:");
            Console.WriteLine("Name: " + name);
            Console.WriteLine("Numbers Array: " + string.Join(", ", numbers));
        }
    }
}

Value Types:
Age: 21
Price: 199.99
Is Student? True

Reference Types:
Name: Megha
Numbers Array: 1, 2, 3, 4, 5
        

This example demonstrates both value types and reference types in C#:

  • Value Types: int, double, bool store actual data.
  • Reference Types: string, array store the memory address of the data.
  • Output: Displays both types separately for clarity.
  • string.Join is used to print array elements neatly.

Best Practices:

  • Use meaningful variable names (age, name, numbers).
  • Keep value and reference types organized for readability.
  • Always initialize variables before using them.
Using Visual Studio:
  1. Open Visual Studio.
  2. Go to File → New → Project → Console App.
  3. Paste the code in Program.cs.
  4. Press F5 to run → Output appears in the console.
Using Command-line:
  1. Save file as VariableDemo.cs.
  2. Open Command Prompt and navigate to the file directory.
  3. Compile: csc VariableDemo.cs
  4. Execute: VariableDemo
`