CodeBlanks Logo Icon CodeBlanks

Floating-point types

C# course · Beginner · Lesson 14/116

Learn double, float and decimal types and their precision differences.

Reference types

Reference types do not store data directly; they hold a reference (address) to it. string and object are core reference types in C#.

These types live on the heap; a variable stores only the address of the data. When you assign one variable to another, the address is copied, so both point to the same data.

An empty reference is written null. Reference types are efficient for large data because copying an address is cheap.

The object type

object is the root type of C#; it can hold any value. You can assign an int, string, or bool to an object.

When you assign a value type to object, boxing occurs: the value is copied to the heap and the reference points there. Example: object box = 42;

To get it back you must state the type explicitly: int n = (int)box;. This is called unboxing and is covered in the next lesson.

Exercise Print a string and an object

Assign "Alex" to a string name variable. Assign 100 to an object data variable. Then print both on their own lines with Console.WriteLine.

Show example solution
Write string name = "Alex"; and object data = 100;, then print them with Console.WriteLine.
Example solution:
using System;
class Program {
    static void Main() {
        string name = "Alex";
        object data = 100;
        Console.WriteLine(name);
        Console.WriteLine(data);
    }
}

Test yourself

  1. Match each type to its memory region

    string
    text (heap)
    int
    whole number (stack)
    object
    any type (heap)
    bool
    logic (stack)
  2. Which one is a reference type?

    • int n = 5;
    • bool ok = true;
    • string s = "hello";
    • char c = 'X';
    Show answer

    string s = "hello"; — Correct! string is a reference type and lives on the heap.

  3. Assign an int to an object variable

    object box = ____;
    Show answer
    object box = 42;

All lessons in Beginner