Skip to content
Learn Netverks

Lesson

Step 22/36 61% through track

generics-csharp

Generics

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~2 min
Level
advanced

This lesson

This lesson teaches Generics: the syntax, patterns, and safety habits you need before advancing in C#.

Generics avoid boxing and enable reusable libraries—collections and APIs are generic-first in .NET.

You will apply Generics in contexts like: .NET services, Unity games, and Windows-centric tooling.

Write C# with Console.WriteLine (top-level or Program), click Run on server—the dev runner uses dotnet build/run on a temp net8 project (requires .NET SDK; LEARNING_RUNNER_ENABLED=true).

When pointers, structs, and basic control flow from intermediate lessons are familiar.

Generics let you write type-safe code parameterized by types—List<T>, Dictionary<TKey, TValue>, and your own Stack<T>. Unlike C++ templates, C# generics are reified at runtime for reference types with shared JIT code where possible.

Generic class

class Box<T> {
    public T Value { get; }
    public Box(T value) => Value = value;
}

Constraints

static T Max<T>(T a, T b) where T : IComparable<T> {
    return a.CompareTo(b) >= 0 ? a : b;
}

Constraints limit T to types with required members—catch errors at compile time, similar to bounded generics in Java.

Important interview questions and answers

  1. Q: Generics vs object boxes?
    A: Generics avoid casts and boxing for value types—better performance and type safety.
  2. Q: Covariance?
    A: IEnumerable<out T> allows substituting derived types in read-only scenarios.

Self-check

  1. What keyword constrains T to have CompareTo?
  2. Why not use ArrayList of object today?

Tip: Generic types are reified at runtime in .NET—unlike Java erasure, List<int> and List<string> are distinct types.

Interview prep

Generics vs templates?

C# generics are reified at runtime with shared JIT code for reference types; C++ templates instantiate per type at compile time.

where T : constraint?

Restricts type parameters—e.g. where T : class, where T : new(), or interface requirements.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • where T : class?
  • Covariance?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump