Skip to content
dreamcode
dreamcode
Map
Generics
Lesson 12 of 21
+15 XP on finish
C# INTERMEDIATEChapter 4 · C# Intermediate

Generics and type safety

Generics introduce the concept of type parameters. They let you design classes and methods that defer the specification of types until instantiated.

Worked example
class Box<T> {
    public T Content { get; set; }
}
// Usage:
Box<int> intBox = new Box<int> { Content = 123 };
Box<string> strBox = new Box<string> { Content = "Vega" };

How it reads

  • <T> is the placeholder for the generic type parameter
  • Box<int> substitutes the integer type for T in that specific instance
Cloud tip: Generics maximize code reuse, type safety, and performance, avoiding boxing/unboxing overhead.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. What represents the type parameter placeholder in generics?
  2. 2. Why are generics preferred over using Object for collections?
Answer every question to unlock the next lesson.