\
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
Data Types in C#

What are Data Types?

When we write a C# program, we often need to store and process different types of information like numbers, text, dates, or logical values. To handle each type correctly, C# provides Data Types.

Many developers stick to only a few data types like int, string, double, bool, and DateTime. This might cause unnecessary memory usage or performance issues.
Example:
  • Using int for values between 0–255 wastes memory; byte is more efficient.
  • Using double for two decimal points is overkill; float or decimal might be better.
Why Choosing the Right Data Type Matters?
  • Memory Usage: Less memory = Better performance
  • Execution Speed: Smaller data = Faster processing
  • Code Clarity: Clear data type choice = Easier understanding

Why Do We Need Data Types in C#?

Data types tell the compiler:

  • How much memory to allocate
  • What kind of operations are allowed on the data
  • How to handle different data like numbers, text, and dates efficiently

✅ All these together make the base structure of a simple C# program.

What is a Data Type in C#?

In C#, a Data Type defines:

Memory Size

Specifies how much memory the variable uses.

Data Range

Defines the min & max value that can be stored.

Legal Operations

Specifies valid operations on that data type.

Expression Results

Specifies the output type of expressions.

Definition: A Data Type is a keyword in C# that defines memory size, data range, legal operations, and the type of result produced by expressions using that data.

Different Types of Data Types in C#

A Data Type in C# specifies the type of data that a variable can store. It helps the compiler understand the memory size, data range, and valid operations for that variable. Some common data types include integer, floating-point, boolean, character, string, and more.

C# Data Types Diagram

Diagram: C# Data Types Overview

Types of Data Types
  • 1. Value Types – int, float, char, bool, etc.
  • 2. Reference Types – string, object, arrays, classes.
  • 3. Pointer Types – Used in unsafe code for memory addresses.
  • 4. Nullable Types – Allow storing null with value types.
Note: C# provides both Value Types and Reference Types, ensuring memory optimization and better performance when chosen wisely.

Value Data Types in C#

The Value Data Type in C# stores the actual value directly in the memory. Examples include int, char, bool, float, etc. All these data types are based on struct in C#, and structs are value types.

Types of Value Data Types
  • Predefined Data Types: int, bool, char, long, double, float, etc.
  • User-defined Data Types: Structure (struct), Enumeration (enum), etc.

Computers can only understand binary digits (0s and 1s). Any information like text, numbers, images, or documents is first converted into binary format before being stored or processed. Let's see how the letter 'A' is represented in a computer:

Conversion Steps
  • Step 1: Original Data → 'A'
  • Step 2: ASCII Code → 65
  • Step 3: Binary Equivalent → 01000001
  • Step 4: Stored as 8 bits → 1 Byte
Note: Developers use decimal format in languages like C#, while the computer automatically converts it to binary format internally.
Data Representation in Memory
Data Representation in Memory

Visual: How Value Data Types store data in memory

Key Point: Value types hold data directly on the stack, which makes access faster compared to reference types.

Byte Data Type in C#

The byte data type in C# is an unsigned 8-bit integer that stores whole numbers ranging from 0 to 255. It is commonly used for memory-efficient numeric storage and binary data processing.

Storage Size

1 Byte (8 bits)

Range

0 to 255

Default Value

0

Type

Value Type (struct)

Syntax
byte variableName = value;
Example
using System;

class Program
{
    static void Main()
    {
        byte age = 25;
        Console.WriteLine("Age: " + age);
    }
}
Output
Age: 25
When to Use
  • When memory optimization is required.
  • For numeric values that are always in the range 0–255.
  • Ideal for binary data like files, images, and streams.
Key Point: The byte data type is perfect for small, positive integers and binary data handling.
Example: Byte & SByte Data Types in C#

Program: ByteSByteDemo.cs


using System;

class Program
{
    static void Main()
    {
        byte b = 200;      // Byte: 0 to 255
        sbyte sb = -100;   // SByte: -128 to 127

        Console.WriteLine("Byte Value: " + b);
        Console.WriteLine("SByte Value: " + sb);
    }
}

Byte Value: 200
SByte Value: -100
        

This example shows both Byte and SByte usage in C#:

  • Byte: Stores only positive numbers (0–255).
  • SByte: Stores both negative & positive numbers (-128 to 127).
  • Both are Value Types and store data directly in memory.

When to use:

  • Use Byte when values are always positive.
  • Use SByte when negative values are also required.
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 ByteSByteDemo.cs.
  2. Open Command Prompt and navigate to the file directory.
  3. Compile: csc ByteSByteDemo.cs
  4. Execute: ByteSByteDemo

🔢 int in C#


1️⃣ What is int?

int in C# is a 32-bit signed integer data type used to store whole numbers between -2,147,483,648 and 2,147,483,647.

2️⃣ Why use int?

We use int when we need to store numeric values without decimals, like counters, IDs, or total quantities.

3️⃣ Where to use int?

  • Loop counters in for loops
  • Storing age, quantity, or scores
  • Mathematical calculations
  • Indexes for arrays or collections

4️⃣ How to use int?

using System;
class Program
{
    static void Main()
    {
        int age = 25; // Variable Declaration & Initialization
        int year = DateTime.Now.Year;
        Console.WriteLine($"Age: {age}, Current Year: {year}");
    }
}
        

5️⃣ Advantages

  • Simple and easy to use
  • Efficient for whole number calculations
  • Consumes less memory than long

6️⃣ Disadvantages

  • Cannot store decimal values
  • Limited range (-2.1B to 2.1B)
  • May cause overflow if range exceeded

Conclusion: Use int when you need whole numbers and memory efficiency.

Example: int Data Type in C#

Program: IntDataTypeDemo.cs


using System;

class IntDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        int a = 25;
        int b = 10;

        // 2. Arithmetic Operations
        int sum = a + b;
        int product = a * b;
        int difference = a - b;
        int quotient = a / b;

        // 3. Conditional Check
        if (a > b)
            Console.WriteLine($"{a} is greater than {b}");

        // 4. Loop Example: Print first 5 numbers
        Console.WriteLine("First 5 Numbers:");
        for (int i = 1; i <= 5; i++)
            Console.Write(i + " ");

        // 5. Range of int
        Console.WriteLine("\nMin Value: " + int.MinValue);
        Console.WriteLine("Max Value: " + int.MaxValue);

        // 6. Display Results
        Console.WriteLine($"Sum: {sum}, Product: {product}, Difference: {difference}, Quotient: {quotient}");
    }
}

25 is greater than 10
First 5 Numbers:
1 2 3 4 5 
Min Value: -2147483648
Max Value: 2147483647
Sum: 35, Product: 250, Difference: 15, Quotient: 2
        

This example covers all key aspects of int in C#:

  • Declaration & Initialization: int a = 25;
  • Arithmetic: +, -, *, / on int values.
  • Conditions: Using if-statement with int.
  • Loops: for-loop example using int counter.
  • Range: int.MinValue & int.MaxValue for limits.

When to use:

  • When you need whole numbers in calculations.
  • For loop counters, indexing, and numeric operations.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as IntDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc IntDataTypeDemo.cs
  5. Run: IntDataTypeDemo

🌊 float in C#


1️⃣ What is float?

float in C# is a 32-bit single-precision floating point data type used to store real numbers (numbers with decimals) in the range of approximately ±1.5e−45 to ±3.4e38.

2️⃣ Why use float?

We use float when we need to store decimal numbers but want to save memory compared to double.

3️⃣ Where to use float?

  • Storing measurements like height, weight
  • Representing currency values (approx.)
  • Scientific calculations with limited precision
  • Graphics programming (coordinates, scaling)

4️⃣ How to use float?

using System;
class Program
{
    static void Main()
    {
        float price = 99.75f;  // 'f' suffix is mandatory for float literals
        float tax = 5.25f;
        Console.WriteLine($"Price: {price}, Tax: {tax}");
    }
}
        

5️⃣ Advantages

  • Stores decimal numbers efficiently
  • Consumes less memory than double
  • Fast for scientific calculations with lower precision

6️⃣ Disadvantages

  • Lower precision than double (only ~7 digits)
  • Not suitable for financial calculations needing high accuracy
  • Can cause rounding errors in large calculations

Conclusion: Use float when approximate values are acceptable and you want to save memory over double.

Example: float Data Type in C#

Program: FloatDataTypeDemo.cs


using System;

class FloatDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        float length = 12.5f;
        float width = 7.3f;

        // 2. Arithmetic Operations
        float area = length * width;
        float perimeter = 2 * (length + width);

        // 3. Comparison
        if (length > width)
            Console.WriteLine($"Length {length} is greater than Width {width}");

        // 4. Range of float
        Console.WriteLine("Min Value: " + float.MinValue);
        Console.WriteLine("Max Value: " + float.MaxValue);

        // 5. Display Results
        Console.WriteLine($"Area: {area}, Perimeter: {perimeter}");
    }
}

Length 12.5 is greater than Width 7.3
Min Value: -3.402823E+38
Max Value: 3.402823E+38
Area: 91.25, Perimeter: 39.6
        

This example demonstrates the use of float in C#:

  • Declaration & Initialization: float length = 12.5f;
  • Arithmetic: Multiplication & addition with float values.
  • Comparison: Using if-statement with float values.
  • Range: float.MinValue & float.MaxValue show limits.

When to use:

  • When decimals are needed but precision is less important.
  • When saving memory compared to double.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as FloatDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc FloatDataTypeDemo.cs
  5. Run: FloatDataTypeDemo

💠 double in C#


1️⃣ What is double?

double in C# is a 64-bit double-precision floating point data type used to store real numbers with high precision, in the range of approximately ±5.0e−324 to ±1.7e308.

2️⃣ Why use double?

We use double when we need high precision for real numbers such as in scientific, engineering, or financial calculations.

3️⃣ Where to use double?

  • Scientific and engineering computations
  • Mathematical formulas requiring high precision
  • Financial calculations with large numbers
  • Complex simulations and modeling

4️⃣ How to use double?

using System;
class Program
{
    static void Main()
    {
        double radius = 7.5;  // No suffix needed for double literals
        double pi = 3.14159265359;
        double area = pi * radius * radius;
        Console.WriteLine($"Radius: {radius}, Area: {area}");
    }
}
        

5️⃣ Advantages

  • High precision for decimal numbers
  • Large range for storing real numbers
  • Standard choice for scientific calculations

6️⃣ Disadvantages

  • Consumes more memory (8 bytes) than float
  • Not suitable for exact decimal values like money (use decimal)

Conclusion: Use double when high precision and wide range are required.

Example: double Data Type in C#

Program: DoubleDataTypeDemo.cs


using System;

class DoubleDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        double length = 15.75;
        double width = 8.45;

        // 2. Arithmetic Operations
        double area = length * width;
        double perimeter = 2 * (length + width);

        // 3. Comparison
        if (length > width)
            Console.WriteLine($"Length {length} is greater than Width {width}");

        // 4. Range of double
        Console.WriteLine("Min Value: " + double.MinValue);
        Console.WriteLine("Max Value: " + double.MaxValue);

        // 5. Display Results
        Console.WriteLine($"Area: {area}, Perimeter: {perimeter}");
    }
}

Length 15.75 is greater than Width 8.45
Min Value: -1.79769313486232E+308
Max Value: 1.79769313486232E+308
Area: 133.0875, Perimeter: 48.4
        

This example demonstrates the use of double in C#:

  • Declaration & Initialization: double length = 15.75;
  • Arithmetic: Multiplication & addition with double values.
  • Comparison: Using if-statement with double values.
  • Range: double.MinValue & double.MaxValue show limits.

When to use:

  • When high precision decimals are needed.
  • When larger range than float is required.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as DoubleDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc DoubleDataTypeDemo.cs
  5. Run: DoubleDataTypeDemo

💰 decimal in C#


1️⃣ What is decimal?

decimal in C# is a 128-bit precise decimal data type with 28-29 significant digits, ideal for financial and monetary calculations where exact decimal representation is required.

2️⃣ Why use decimal?

We use decimal when accuracy in fractional values is more important than performance, such as in banking, accounting, or financial systems.

3️⃣ Where to use decimal?

  • Banking and financial applications
  • Tax and interest calculations
  • Currency and money transactions
  • Any application requiring precise decimal values

4️⃣ How to use decimal?

using System;
class Program
{
    static void Main()
    {
        decimal price = 199.99m;  // 'm' suffix is mandatory for decimal literals
        decimal tax = 18.75m;
        decimal total = price + tax;
        Console.WriteLine($"Price: {price}, Tax: {tax}, Total: {total}");
    }
}
        

5️⃣ Advantages

  • High precision for financial calculations
  • Avoids rounding errors common with float/double
  • Exact decimal representation

6️⃣ Disadvantages

  • Slower performance compared to float/double
  • Consumes more memory (16 bytes)

Conclusion: Use decimal when financial accuracy is crucial, even if it uses more memory and is slower.

Example: decimal Data Type in C#

Program: DecimalDataTypeDemo.cs


using System;

class DecimalDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        decimal principal = 10000.50m;
        decimal rate = 7.5m;
        decimal time = 5m;

        // 2. Simple Interest Calculation
        decimal interest = (principal * rate * time) / 100;

        // 3. Total Amount
        decimal total = principal + interest;

        // 4. Range of decimal
        Console.WriteLine("Min Value: " + decimal.MinValue);
        Console.WriteLine("Max Value: " + decimal.MaxValue);

        // 5. Display Results
        Console.WriteLine($"Principal: {principal}, Interest: {interest}, Total: {total}");
    }
}

Min Value: -79228162514264337593543950335
Max Value: 79228162514264337593543950335
Principal: 10000.50, Interest: 3750.1875, Total: 13750.6875
        

This example demonstrates the use of decimal in C#:

  • Declaration & Initialization: decimal principal = 10000.50m;
  • Arithmetic: Simple Interest calculation with decimal values.
  • Range: decimal.MinValue & decimal.MaxValue show limits.
  • Total: Final amount with interest.

When to use:

  • For money calculations needing exact precision.
  • For financial or tax-related systems.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as DecimalDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc DecimalDataTypeDemo.cs
  5. Run: DecimalDataTypeDemo

🔤 char in C#


1️⃣ What is char?

char in C# is a 16-bit Unicode character data type used to store a single character like 'A', '1', or '$'. It uses the System.Char struct internally.

2️⃣ Why use char?

We use char when we need to store and work with a single character instead of an entire string, such as reading key inputs or processing individual characters.

3️⃣ Where to use char?

  • Reading a single character input from the user
  • Checking if a character is a letter, digit, or symbol
  • Creating character arrays for string manipulation
  • Storing special symbols or escape characters

4️⃣ How to use char?

using System;
class Program
{
    static void Main()
    {
        char grade = 'A';  // Single character in single quotes
        char symbol = '#';
        Console.WriteLine($"Grade: {grade}, Symbol: {symbol}");
    }
}
        

5️⃣ Advantages

  • Stores a single Unicode character efficiently
  • Supports escape sequences like '\n', '\t'
  • Lightweight compared to strings

6️⃣ Disadvantages

  • Only for single characters, not text or words
  • Limited use in modern applications compared to strings

Conclusion: Use char when you need to store or manipulate a single character, such as in character validation or user inputs.

Example: char Data Type in C#

Program: CharDataTypeDemo.cs


using System;

class CharDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        char letter = 'C';
        char digit = '9';
        char symbol = '$';

        // 2. Checking character types
        if (char.IsLetter(letter))
            Console.WriteLine($"{letter} is a Letter");

        if (char.IsDigit(digit))
            Console.WriteLine($"{digit} is a Digit");

        if (char.IsSymbol(symbol))
            Console.WriteLine($"{symbol} is a Symbol");

        // 3. Escape sequences
        char newline = '\n';
        Console.WriteLine("Hello" + newline + "World");

        // 4. Display Values
        Console.WriteLine($"Characters: {letter}, {digit}, {symbol}");
    }
}

C is a Letter
9 is a Digit
$ is a Symbol
Hello
World
Characters: C, 9, $
        

This example demonstrates the use of char in C#:

  • Declaration & Initialization: char letter = 'C';
  • Character Checking: char.IsLetter, char.IsDigit, char.IsSymbol methods.
  • Escape Sequences: '\n' for newline used.
  • Output: Shows multiple character examples.

When to use:

  • When only single character storage is needed.
  • For validating or processing individual characters.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as CharDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc CharDataTypeDemo.cs
  5. Run: CharDataTypeDemo

✅ bool in C#


1️⃣ What is bool?

bool in C# is a Boolean data type that can store only two values: true or false. It is defined in the System.Boolean structure.

2️⃣ Why use bool?

We use bool when we need to represent conditions, logical states, or flags, such as yes/no, on/off, success/failure situations.

3️⃣ Where to use bool?

  • Decision making (if-else conditions)
  • Loop control conditions
  • Flags for program states (e.g., IsRunning = true)
  • Storing results of logical comparisons

4️⃣ How to use bool?

using System;
class Program
{
    static void Main()
    {
        bool isPassed = true;
        bool isAdmin = false;
        Console.WriteLine($"Passed: {isPassed}, Admin: {isAdmin}");
    }
}
        

5️⃣ Advantages

  • Simple and memory efficient (1 byte)
  • Ideal for conditional and logical operations
  • Makes code more readable and clear

6️⃣ Disadvantages

  • Stores only true/false; no other values
  • Not suitable for numeric or text data

Conclusion: Use bool for conditions, flags, and logical expressions where only true or false values are needed.

Example: bool Data Type in C#

Program: BoolDataTypeDemo.cs


using System;

class BoolDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        bool isStudent = true;
        bool isTeacher = false;

        // 2. Logical Comparisons
        int age = 20;
        bool isAdult = age >= 18;

        // 3. Using in conditions
        if (isAdult)
            Console.WriteLine("You are an adult.");

        // 4. Display Values
        Console.WriteLine($"Student: {isStudent}, Teacher: {isTeacher}, Adult: {isAdult}");
    }
}

You are an adult.
Student: True, Teacher: False, Adult: True
        

This example demonstrates the use of bool in C#:

  • Initialization: bool isStudent = true;
  • Logical Comparisons: Used with relational operators like >=.
  • Conditions: if statements check bool values directly.
  • Output: Shows results of conditions and bool values.

When to use:

  • For decision-making in programs.
  • For storing logical states like true/false flags.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as BoolDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc BoolDataTypeDemo.cs
  5. Run: BoolDataTypeDemo

🔠 string in C#


1️⃣ What is string?

string in C# is a sequence of characters used to store text. It is an immutable reference type in the System.String class.

2️⃣ Why use string?

We use string to store and manipulate text, names, messages, or any sequence of characters required in the program.

3️⃣ Where to use string?

  • Storing names, addresses, and messages
  • Manipulating text in applications
  • Working with user input and output
  • Creating formatted messages and reports

4️⃣ How to use string?

using System;
class Program
{
    static void Main()
    {
        string name = "John";       // String literal
        string greeting = "Hello";  // Another string
        string message = greeting + " " + name; // Concatenation
        Console.WriteLine(message);
    }
}
        

5️⃣ Advantages

  • Easy to store and manipulate text
  • Supports many inbuilt methods like Substring, Replace, Split
  • Supports string interpolation for clean formatting

6️⃣ Disadvantages

  • Immutable – every change creates a new string object
  • For heavy text manipulations, StringBuilder is better

Conclusion: Use string for storing and processing text in C# programs.

Example: string Data Type in C#

Program: StringDataTypeDemo.cs


using System;

class StringDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        string firstName = "Alice";
        string lastName = "Johnson";

        // 2. Concatenation
        string fullName = firstName + " " + lastName;

        // 3. String Interpolation
        string message = $"Welcome, {fullName}!";

        // 4. String Methods
        Console.WriteLine("Uppercase: " + fullName.ToUpper());
        Console.WriteLine("Length: " + fullName.Length);

        // 5. Display Results
        Console.WriteLine(message);
    }
}

Uppercase: ALICE JOHNSON
Length: 13
Welcome, Alice Johnson!
        

This example demonstrates the use of string in C#:

  • Concatenation: Using + operator to join strings.
  • Interpolation: Using $"..." for cleaner formatting.
  • Methods: ToUpper(), Length show inbuilt functionalities.

When to use:

  • Whenever textual data is required.
  • For displaying and processing text in applications.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as StringDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc StringDataTypeDemo.cs
  5. Run: StringDataTypeDemo

🧩 object in C#


1️⃣ What is object?

object in C# is the base type from which all other data types are derived. It can store any type of data including value types, reference types, and user-defined types.

2️⃣ Why use object?

We use object when we want a generalized data type that can store data of any type and provide flexibility.

3️⃣ Where to use object?

  • When type is not known at compile time
  • Storing heterogeneous data in collections
  • Passing data between methods or layers
  • Working with reflection or dynamic programming

4️⃣ How to use object?

using System;
class Program
{
    static void Main()
    {
        object obj1 = 100;        // int stored as object
        object obj2 = "Hello";    // string stored as object
        Console.WriteLine(obj1);
        Console.WriteLine(obj2);
    }
}
        

5️⃣ Advantages

  • Can store any type of data
  • Base type for all data types in C#
  • Provides flexibility for generic programming

6️⃣ Disadvantages

  • Boxing and unboxing overhead for value types
  • Loss of compile-time type checking

Conclusion: Use object for storing data when type is unknown at compile time.

Example: object Data Type in C#

Program: ObjectDataTypeDemo.cs


using System;

class ObjectDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        object obj1 = 123;                  // int stored as object
        object obj2 = "C# Programming";     // string stored as object
        object obj3 = 45.67;                // double stored as object

        // 2. Display Values
        Console.WriteLine("Integer Object: " + obj1);
        Console.WriteLine("String Object: " + obj2);
        Console.WriteLine("Double Object: " + obj3);

        // 3. Type Casting (Unboxing)
        int num = (int)obj1;
        Console.WriteLine("Unboxed Integer: " + num);

        // 4. Type Checking
        if (obj2 is string)
            Console.WriteLine("obj2 is a string");
    }
}

Integer Object: 123
String Object: C# Programming
Double Object: 45.67
Unboxed Integer: 123
obj2 is a string
        

This example demonstrates the use of object in C#:

  • Declaration: Any data type can be stored in object.
  • Unboxing: Casting back to original type when needed.
  • Type Checking: Using is keyword for safe operations.

When to use:

  • When data type is unknown at compile time.
  • For heterogeneous collections or generic programming.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as ObjectDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc ObjectDataTypeDemo.cs
  5. Run: ObjectDataTypeDemo

🧩 object in C#


1️⃣ What is object?

object in C# is the base type from which all other data types are derived. It can store any type of data including value types, reference types, and user-defined types.

2️⃣ Why use object?

We use object when we want a generalized data type that can store data of any type and provide flexibility.

3️⃣ Where to use object?

  • When type is not known at compile time
  • Storing heterogeneous data in collections
  • Passing data between methods or layers
  • Working with reflection or dynamic programming

4️⃣ How to use object?

using System;
class Program
{
    static void Main()
    {
        object obj1 = 100;        // int stored as object
        object obj2 = "Hello";    // string stored as object
        Console.WriteLine(obj1);
        Console.WriteLine(obj2);
    }
}
        

5️⃣ Advantages

  • Can store any type of data
  • Base type for all data types in C#
  • Provides flexibility for generic programming

6️⃣ Disadvantages

  • Boxing and unboxing overhead for value types
  • Loss of compile-time type checking

Conclusion: Use object for storing data when type is unknown at compile time.

Example: object Data Type in C#

Program: ObjectDataTypeDemo.cs


using System;

class ObjectDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        object obj1 = 123;                  // int stored as object
        object obj2 = "C# Programming";     // string stored as object
        object obj3 = 45.67;                // double stored as object

        // 2. Display Values
        Console.WriteLine("Integer Object: " + obj1);
        Console.WriteLine("String Object: " + obj2);
        Console.WriteLine("Double Object: " + obj3);

        // 3. Type Casting (Unboxing)
        int num = (int)obj1;
        Console.WriteLine("Unboxed Integer: " + num);

        // 4. Type Checking
        if (obj2 is string)
            Console.WriteLine("obj2 is a string");
    }
}

Integer Object: 123
String Object: C# Programming
Double Object: 45.67
Unboxed Integer: 123
obj2 is a string
        

This example demonstrates the use of object in C#:

  • Declaration: Any data type can be stored in object.
  • Unboxing: Casting back to original type when needed.
  • Type Checking: Using is keyword for safe operations.

When to use:

  • When data type is unknown at compile time.
  • For heterogeneous collections or generic programming.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as ObjectDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc ObjectDataTypeDemo.cs
  5. Run: ObjectDataTypeDemo

⚡ dynamic in C#


1️⃣ What is dynamic?

dynamic in C# is a data type where the type checking happens at runtime instead of compile time. It allows you to store any data type and change it at runtime.

2️⃣ Why use dynamic?

Use dynamic when working with data that changes at runtime or when you are unsure about the type at compile time.

3️⃣ Where to use dynamic?

  • Working with COM objects
  • Interacting with dynamic languages like Python
  • Processing JSON or XML where schema may change
  • Reflection or runtime object manipulation

4️⃣ How to use dynamic?

using System;
class Program
{
    static void Main()
    {
        dynamic data = 10;       // int
        Console.WriteLine(data);

        data = "Hello";          // string
        Console.WriteLine(data);

        data = 99.99;            // double
        Console.WriteLine(data);
    }
}
        

5️⃣ Advantages

  • Flexibility to store any type
  • Useful when type is unknown until runtime
  • Simplifies interaction with dynamic languages or COM objects

6️⃣ Disadvantages

  • No compile-time type checking
  • Runtime errors possible if members do not exist
  • Slight performance overhead

Conclusion: Use dynamic when type information is not known at compile time or for runtime flexibility.

Example: dynamic Data Type in C#

Program: DynamicDataTypeDemo.cs


using System;

class DynamicDataTypeDemo
{
    static void Main()
    {
        // 1. Declaration & Initialization
        dynamic value = 50;
        Console.WriteLine("Value as int: " + value);

        // 2. Changing Type at Runtime
        value = "Dynamic in C#";
        Console.WriteLine("Value as string: " + value);

        // 3. Assigning a Double
        value = 123.45;
        Console.WriteLine("Value as double: " + value);

        // 4. Using dynamic in operations
        dynamic num1 = 10;
        dynamic num2 = 20;
        Console.WriteLine("Sum: " + (num1 + num2));
    }
}

Value as int: 50
Value as string: Dynamic in C#
Value as double: 123.45
Sum: 30
        

This example demonstrates the use of dynamic in C#:

  • Dynamic Type: Type decided at runtime.
  • Flexibility: Same variable can hold different data types.
  • Operations: Can perform arithmetic if data supports it.

When to use:

  • When dealing with runtime data sources.
  • When working with dynamic or COM objects.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as DynamicDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc DynamicDataTypeDemo.cs
  5. Run: DynamicDataTypeDemo

📝 var in C#


1️⃣ What is var?

var in C# is an implicitly typed local variable where the type is inferred by the compiler at compile time based on the assigned value.

2️⃣ Why use var?

Use var to reduce code length and improve readability, especially when the type name is long or complex.

3️⃣ Where to use var?

  • When the type is clear from the right-hand side value
  • Working with LINQ queries or anonymous types
  • Local variables inside methods

4️⃣ How to use var?

using System;
class Program
{
    static void Main()
    {
        var num = 100;           // int
        var message = "Hello";   // string
        var price = 99.99;       // double

        Console.WriteLine(num);
        Console.WriteLine(message);
        Console.WriteLine(price);
    }
}
        

5️⃣ Advantages

  • Reduces code length
  • Improves readability for complex types
  • Type-safe since type is inferred at compile time

6️⃣ Disadvantages

  • Type must be known at compile time
  • Cannot be used for class-level variables
  • Overuse can reduce code clarity

Conclusion: Use var for local variables when type is obvious or to simplify complex types.

Example: var Data Type in C#

Program: VarDataTypeDemo.cs


using System;

class VarDataTypeDemo
{
    static void Main()
    {
        // 1. Implicit Typing
        var number = 200;             // int
        var name = "C# Programming";  // string
        var amount = 123.45;          // double

        // 2. Display Values
        Console.WriteLine("Number: " + number);
        Console.WriteLine("Name: " + name);
        Console.WriteLine("Amount: " + amount);

        // 3. Arithmetic using var
        var sum = number + 50;
        Console.WriteLine("Sum: " + sum);
    }
}

Number: 200
Name: C# Programming
Amount: 123.45
Sum: 250
        

This example demonstrates the use of var in C#:

  • Implicit Typing: Compiler decides the type at compile time.
  • Type Safety: Type remains fixed after initialization.
  • Readability: Simplifies code for complex data types.

When to use:

  • For local variables with obvious types.
  • With anonymous types or LINQ queries.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as VarDataTypeDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc VarDataTypeDemo.cs
  5. Run: VarDataTypeDemo

🗂️ Arrays in C#


1️⃣ What is an Array?

An Array in C# is a collection of variables of the same type stored in a single name. It allows storing multiple values together in contiguous memory locations.

2️⃣ Why use Array?

Arrays make it easier to handle large amounts of data using a single variable name instead of multiple variables.

3️⃣ Where to use Array?

  • Storing multiple values of the same type
  • Data processing tasks like sorting & searching
  • Handling lists of numbers, strings, or objects

4️⃣ How to use Array?

using System;
class Program
{
    static void Main()
    {
        int[] numbers = {10, 20, 30, 40, 50};  // Array initialization
        Console.WriteLine(numbers[0]);         // Access first element
    }
}
        

5️⃣ Advantages

  • Stores multiple values in a single variable
  • Easy to traverse using loops
  • Efficient for data storage & processing

6️⃣ Disadvantages

  • Fixed size – cannot change once declared
  • Stores data of only one type
  • No built-in methods for dynamic resizing

Conclusion: Use Arrays for storing and processing fixed-size data of the same type.

Example: Array in C#

Program: ArrayDemo.cs


using System;

class ArrayDemo
{
    static void Main()
    {
        // 1. Array Declaration & Initialization
        int[] numbers = {10, 20, 30, 40, 50};

        // 2. Display Array Elements
        Console.WriteLine("Array Elements:");
        for(int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine(numbers[i]);
        }

        // 3. Sum of Array Elements
        int sum = 0;
        foreach(int num in numbers)
        {
            sum += num;
        }
        Console.WriteLine("Sum: " + sum);
    }
}

Array Elements:
10
20
30
40
50
Sum: 150
        

This example demonstrates the use of Arrays in C#:

  • Declaration & Initialization: Stores multiple integers.
  • Access & Display: Used for loop to print values.
  • Sum Calculation: foreach loop for summation.

When to use:

  • When you need a fixed-size collection.
  • For numeric calculations and data storage.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as ArrayDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc ArrayDemo.cs
  5. Run: ArrayDemo

❓ Nullable Types in C#


1️⃣ What is a Nullable Type?

A Nullable Type in C# allows value types (like int, double) to hold a null value in addition to their normal range. It is declared using a ? after the type. Example: int?, double?.

2️⃣ Why use Nullable?

Nullable types help when dealing with missing or unknown data, especially with databases or optional values.

3️⃣ Where to use Nullable?

  • Database fields where data can be missing
  • Optional user inputs
  • Situations requiring both numeric and null values

4️⃣ How to use Nullable?

using System;
class Program
{
    static void Main()
    {
        int? num = null;      // Nullable int
        if(num.HasValue)
            Console.WriteLine(num.Value);
        else
            Console.WriteLine("Value is null");
    }
}
        

5️⃣ Advantages

  • Allows value types to store null values
  • Prevents runtime errors with missing data
  • Useful for database operations

6️⃣ Disadvantages

  • Needs extra checks for null values
  • May complicate logic if overused

Conclusion: Use Nullable Types for handling missing or optional data safely in C#.

Example: Nullable Types in C#

Program: NullableDemo.cs


using System;

class NullableDemo
{
    static void Main()
    {
        // 1. Nullable int
        int? score = null;

        // 2. Check for null
        if (score.HasValue)
            Console.WriteLine("Score: " + score.Value);
        else
            Console.WriteLine("Score is null");

        // 3. Using null-coalescing operator
        int finalScore = score ?? 100;
        Console.WriteLine("Final Score: " + finalScore);
    }
}

Score is null
Final Score: 100
        

This example shows how to use Nullable Types in C#:

  • ? Operator: Makes a value type nullable.
  • HasValue: Checks if the value is null or not.
  • ?? Operator: Provides a default value if null.

When to use:

  • When data can be missing (e.g., DB values).
  • For optional calculations or inputs.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Press F5 → Run the program.
Using Command-line:
  1. Save as NullableDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc NullableDemo.cs
  5. Run: NullableDemo

🖱️ Pointers in C#


1️⃣ What is a Pointer?

A Pointer in C# is a variable that stores the memory address of another variable. Pointers are used in unsafe code blocks as C# normally manages memory automatically.

2️⃣ Why use Pointer?

Pointers allow direct memory access and manipulation, useful for performance-critical applications or working with unmanaged code.

3️⃣ Where to use Pointer?

  • Interacting with unmanaged code or APIs
  • Memory manipulation tasks
  • Performance-sensitive applications

4️⃣ How to use Pointer?

using System;
class Program
{
    unsafe static void Main()
    {
        int num = 20;
        int* ptr = #       // Pointer stores address of num
        Console.WriteLine("Value: " + *ptr);   // Access value using pointer
    }
}
        

5️⃣ Advantages

  • Provides direct memory access
  • Useful for working with unmanaged code
  • Improves performance in some cases

6️⃣ Disadvantages

  • Risk of memory corruption if misused
  • Code becomes harder to maintain
  • Requires unsafe context & permissions

Conclusion: Use Pointers only when necessary, mainly for unmanaged code or performance optimization.

Example: Pointers in C#

Program: PointerDemo.cs


using System;

class PointerDemo
{
    unsafe static void Main()
    {
        int number = 50;
        int* ptr = &number;  // Pointer stores address of number

        Console.WriteLine("Value: " + *ptr);    // Accessing value
        Console.WriteLine("Address: " + (long)ptr); // Displaying memory address
    }
}

Value: 50
Address: 6422292  (example - actual value will vary)
        

This example demonstrates the use of Pointers in C#:

  • & Operator: Gets the address of a variable.
  • * Operator: Accesses the value at the address.
  • Requires unsafe context and /unsafe compiler option.

When to use:

  • When working with unmanaged code.
  • For memory-specific operations.
Using Visual Studio:
  1. Open Visual Studio.
  2. Create Console App project.
  3. Paste the code in Program.cs.
  4. Enable Allow Unsafe Code in project settings.
  5. Press F5 → Run the program.
Using Command-line:
  1. Save as PointerDemo.cs.
  2. Open Command Prompt.
  3. Navigate to the file location.
  4. Compile: csc /unsafe PointerDemo.cs
  5. Run: PointerDemo

📘 C# Data Types Reference

Data Type Description Values / Range Memory Size (Bytes) Memory Type Storage Location Max Value / Limitation Example
Byte 8-bit unsigned integer 0 to 255 1 Value Type Stack 255 byte b = 200;
byte age = 25;
// Age of a person
Sbyte8-bit signed integer-128 to 1271 Value TypeStack127sbyte sb = -100;
sbyte temp = -30;
// Temperature in winter
short16-bit signed integer-32,768 to 32,7672Value TypeStack32,767short s = 30000;
short students = 500;
// Students in school
ushort16-bit unsigned integer0 to 65,5352Value TypeStack65,535ushort us = 60000;
ushort population = 60000;
// Village pop
int32-bit signed integer-2,147,483,648 to 2,147,483,6474Value TypeStack2,147,483,647int age = 25;
int salary = 35000;
// Monthly salary
uint32-bit unsigned integer0 to 4,294,967,2954Value TypeStack4,294,967,295uint u = 3000000000; uint stock = 200000;
// Product stock
long64-bit signed integer-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8078Value TypeStack9,223,372,036,854,775,807long l = 9000000000;
long distance = 15000000000;
// Space distance
ulong64-bit unsigned integer0 to 18,446,744,073,709,551,6158Value TypeStack18,446,744,073,709,551,615ulong ul = 10000000000;
ulong views = 10000000000;
// Video views
float32-bit single precision floating point±1.5e−45 to ±3.4e384Value TypeStackPrecision: ~7 digitsfloat f = 5.5f;
float pi = 3.14f;
// Value of Pi
double64-bit double precision floating point±5.0e−324 to ±1.7e3088Value TypeStackPrecision: ~15-16 digitsdouble d = 19.99;
double price = 199.99;
// Product price
decimal128-bit high-precision floating point±1.0e−28 to ±7.9e2816Value TypeStackPrecision: ~28-29 digitsdecimal dec = 1000.50m;
decimal money = 100000.75m;
// Bank balance
charSingle 16-bit Unicode characterAny Unicode character2Value TypeStackSingle character onlychar grade = 'A';
char grade = 'A';
// Student grade
boolTrue or FalseTrue, False1Value TypeStackOnly two valuesbool isActive = true;
bool isActive = true;
// Is account active?
stringSequence of characters (immutable)Any textDynamic (length × 2)Reference TypeHeapLimited b
y memory
string name = "Megha";
string name = "Megha";
// Person's name
dynamicRuntime type bindingAny data type at runtimeDynamicReference TypeHeapType decided at runtimedynamic val = 10; val = "Hi";
dynamic value = 10; value = "Hello";
varCompile-time type inferenceAny type (decided by compiler)Based on typeReference/ValueStack / HeapCannot change type once assignedvar x = 100;
var city = "Delhi";
// Auto type detection
arrayCollection of similar data typesFixed lengthDepends on elementsReference TypeHeapFixed size, same data typeint[] arr = {1,2,3};
int[] marks = {90, 85, 95};
nullableValue type that can hold nullNull or actual valueBased on typeValue TypeStackAllows null assignmentint? age = null;
int? age = null;
PointerStores memory address (unsafe code)Memory address4 / 8Pointer TypeStack / HeapUsed in unsafe context onlyint* ptr;
// Pointer example