C# ยท Chapter 8 of 46

C# Data Types

C# provides several built-in data types to store different kinds of values: int for whole numbers, double for decimals, char for single characters, bool for true/false, and string for text.

Choosing the right type affects both memory usage and precision. C# is a strongly typed language, meaning every variable's type is checked at compile time.

Syntax
int a;
double b;
char c;
bool d;
string e;

Numeric types

int stores whole numbers, double stores decimal numbers with high precision, float stores decimals with less precision, and decimal is used for precise financial calculations.

Other types

char stores a single character, bool stores true or false, and string stores text made of many characters. Each type has a default value when not explicitly set.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    int a = 5;
    double b = 5.5;
    char c = 'A';
    bool d = true;
    Console.WriteLine(a + " " + b + " " + c + " " + d);
  }
}
Output
5 5.5 A True

Four different data types are declared, initialized and printed.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    string name = "Amy";
    Console.WriteLine(name);
  }
}
Output
Amy

A string variable stores a sequence of characters, like a name.

Key points

  • int, double, char, bool and string are core built-in types.
  • double has more precision than float.
  • decimal is preferred for money-related calculations.
  • C# is strongly typed and checks types at compile time.
๐Ÿ’ก Note: Use decimal instead of double or float when working with currency to avoid rounding errors.

๐Ÿ“ Quick Quiz

1. Which type is best for storing money accurately?

2. Which type stores true or false?

3. Which type stores text made of many characters?