CodeBlanks Logo Icon CodeBlanks

Summary - Data types

C# course · Beginner · Lesson 18/116

Combine integer, floating-point and string types to write a calculation card.

Summary

In this unit you learned the data types of C#. Value types (int, double, char, bool) live on the stack; reference types (string, object) live on the heap.

You saw conversion paths: implicit widening, explicit (int) cast, int.Parse, and the Convert class. With int? you made value types nullable, and ?? supplied a default.

Finally, boxing and unboxing: you boxed a value type into object and took it back. Now you will combine these in a small app.

Exercise Combine nullable and arithmetic

Declare an int age = 20 variable. Declare an int? bonus = null variable. Compute the sum with int total = age + (bonus ?? 5);. Then print total with Console.WriteLine.

Show example solution
int age = 20; int? bonus = null; int total = age + (bonus ?? 5); Console.WriteLine(total);
Example solution:
using System;
class Program {
    static void Main() {
        int age = 20;
        int? bonus = null;
        int total = age + (bonus ?? 5);
        Console.WriteLine(total);
    }
}

Exercise Parse a number and double it

Assign "100" to a string text variable. Convert it with int n = int.Parse(text). Double it with int doubled = n * 2. Then print doubled with Console.WriteLine.

Show example solution
string text = "100"; int n = int.Parse(text); int doubled = n * 2; Console.WriteLine(doubled);
Example solution:
using System;
class Program {
    static void Main() {
        string text = "100";
        int n = int.Parse(text);
        int doubled = n * 2;
        Console.WriteLine(doubled);
    }
}

Test yourself

  1. Which line gives a compile error?

    • int n = 5;
    • double d = 8;
    • int k = 3.7;
    • object o = 10;
    Show answer

    int k = 3.7; — Correct! You cannot implicitly assign a double to an int; an (int) cast is required.

  2. Match each concept to its meaning

    int?
    nullable
    (int)
    cast
    ??
    default
    object
    reference

All lessons in Beginner