C#  

Variables and Data Types in C#

1. What Are Variables? (Simple Definition)

A variable is like a container in memory that stores data.

Think of it like:

  • A water bottle (container) = variable

  • The water inside = value

  • The type of water (500ml, 1 liter) = data type

C# Definition

A variable in C# is a named storage location in memory used to store a value.
It has:

  1. Name

  2. Data Type

  3. Value

Syntax

dataType variableName = value;

Example

int age = 25;
string name = "Sandhiya";
double price = 99.50;

Real-Time Example (Easy Explanation)

Imagine you are building a shopping website:

Variable NameData TypePurpose
productNamestringStore the product name
productPricedoubleStore the price
stockCountintHow many items available
string productName = "Laptop";
double productPrice = 59999.99;
int stockCount = 10;

2. What Are Data Types?

A data type tells the compiler what type of data a variable will store.

C# Data Types Categories

1. Value Types (store data directly)

  • int

  • double

  • float

  • char

  • bool

2. Reference Types (store memory address)

  • string

  • arrays

  • class objects

Common Data Types with Examples

Below are all commonly used data types with simple, real-time examples.

1. int (Integer)

Stores whole numbers (no decimal).

int age = 25;
int stock = 100;

Real-time: Number of items in cart, number of login attempts.

2. double (Decimal Number – high precision)

double salary = 20000.75;
double rating = 4.5;

Real-time: Price, ratings.

3. float (decimal but less precision)

float temperature = 32.5f;

Has ‘f’ at end.

4. decimal (Money values – very accurate)

decimal accountBalance = 10500.75m;

Used for banking, finance.

5. char (Single character)

char grade = 'A';

6. string (Sequence of characters)

string customerName = "Sandhiya";
string email = "[email protected]";

Real-time: Names, messages, emails, addresses.

7. bool (true/false)

bool isVerified = true;
bool isLoggedIn = false;

Real-time: Login success, item isActive, user subscription.

Real-Time Mini Example (All Combined)

Scenario: Online product page

string productName = "Mobile Phone";
int stock = 50;
double price = 14999.99;
bool isAvailable = true;
char category = 'A';

Code Example: Small Console App

using System;

class Program
{
    static void Main()
    {
        string name = "Sandhiya";
        int age = 24;
        double height = 5.4;
        bool isStudent = true;

        Console.WriteLine("Name: " + name);
        Console.WriteLine("Age: " + age);
        Console.WriteLine("Height: " + height);
        Console.WriteLine("Student? " + isStudent);
    }
}

Summary Table

Data TypeExamplePurpose
int20Whole numbers
double20.50Decimal values
decimal100.50mMoney
string"Hello"Text
char'A'Single character
booltrue/falseLogical values