Chapter 17: Generics

1. What are Generics? (Super Simple Analogy)

Imagine you’re building a storage box factory:

  • Without generics → You make one box for integers, one for strings, one for dates… lots of duplicate factories!
  • With generics → You make one smart box factory that can produce boxes for any type you want: Box<int>, Box<string>, Box<DateTime>, Box<Car> — all from one blueprint!

Generics = parameterized types You write code once, and it works perfectly with any type you give it.

2. Generic Classes – The Most Common Use

Syntax:

C#

Usage:

C#

Type safety: If you try intBox.Put(“hello”) → compile error! That’s the magic — generics give you full type safety at compile time.

3. Generic Methods – Reuse Logic for Any Type

You can also make individual methods generic (even inside non-generic classes).

C#

4. Generic Constraints – Control Which Types Are Allowed

Sometimes you need to restrict what types T can be.

Common constraints:

Constraint Meaning Example Use Case
where T : class T must be a reference type (class) For objects that can be null
where T : struct T must be a value type (struct, int, bool…) Performance-critical code
where T : new() T must have a parameterless constructor Creating new instances of T
where T : SomeClass T must inherit from SomeClass Working with specific base classes
where T : ISomeInterface T must implement ISomeInterface Calling interface methods on T
where T : IComparable<T> T must be comparable (can be sorted) Sorting or finding max/min

Real example with constraints:

C#

Another example – Sorting with IComparable

C#

5. Generic Collections – The Power in Real Life

The most common use of generics is in collections (from System.Collections.Generic):

Generic Collection Purpose Example
List<T> Dynamic array (grow/shrink) List<string> names = new();
Dictionary<TKey, TValue> Key-value pairs (fast lookup) Dictionary<int, string> users;
HashSet<T> Unique items (no duplicates) HashSet<int> ids;
Queue<T> / Stack<T> FIFO / LIFO Queue<string> tasks;
LinkedList<T> Efficient insert/remove in middle LinkedList<int> numbers;

Example – Generic List in action

C#

Mini-Project: Generic Stack Machine

C#

Summary – What We Learned Today

  • Generics → write one piece of code that works with any type
  • Generic classes → class MyClass<T>
  • Generic methods → void MyMethod<T>(T param)
  • Constraints → where T : class, where T : new(), where T : IComparable<T>…
  • Generic collections → List<T>, Dictionary<TKey,TValue>, HashSet<T>… – must-use in real apps
  • Benefits → Type safety, performance, reusability, no casting

Your Homework (Super Practical!)

  1. Create a new console project called GenericsMaster
  2. Create a generic class called Pair<TFirst, TSecond> with:
    • Properties: First, Second
    • Method: Swap() (swaps First and Second)
  3. Create a generic method called PrintIfGreater<T> where T : IComparable<T> that takes two T values and prints the larger one
  4. In Program.cs:
    • Use Pair<string, int> for name + age
    • Use Pair<double, DateTime> for price + date
    • Test PrintIfGreater with numbers, strings, and DateTime

Next lesson: LINQ (Language Integrated Query) – we’re going to learn how to query, filter, sort, and transform collections like magic!

You’re doing absolutely fantastic! 🎉 Any part confusing? Want more examples with constraints or multiple type parameters? Just tell me — I’m right here for you! 💙

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *