0Pricing
C# Academy · Lesson

Generics in C#

Learn how generics enable type-safe and reusable code structures.

Generics in C# is a free C# Academy lesson on CoddyKit — lesson 1 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 5 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Generics in C#

Welcome to the first lesson in "Advanced C# Features"! In this lesson, you’ll learn about generics, a powerful feature in C# that allows you to create flexible and reusable code. Let’s get started!

Generics in C# — illustration 1

2

What Are Generics?

Generics are a feature in C# that allows you to define classes, methods, and data structures with a placeholder for the type of data they store or use. Generics enable type safety and code reuse.

Example: A generic list (List<T>) can store elements of any type while ensuring type safety.

3

Creating Generic Classes

You can define a generic class using the <T> syntax, where T represents a type parameter. Example:

Key Point: Use generics to create classes that work with any data type while maintaining type safety.

using System;

class GenericBox<T> {
    public T Value { get; set; }

    public void Display() {
        Console.WriteLine("Value: " + Value);
    }
}

class Program {
    static void Main() {
        GenericBox<int> intBox = new GenericBox<int> { Value = 42 };
        intBox.Display(); // Outputs: Value: 42

        GenericBox<string> stringBox = new GenericBox<string> { Value = "Hello, Generics!" };
        stringBox.Display(); // Outputs: Value: Hello, Generics!
    }
}

4

Creating Generic Methods

You can define a generic method within a class. Example:

Tip: Use generic methods for operations that apply to multiple data types.

using System;

class Program {
    static void Main() {
        PrintValue(42);
        PrintValue("Generics are powerful!");
    }

    static void PrintValue<T>(T value) {
        Console.WriteLine("Value: " + value);
    }
}

5

Generic Constraints

Constraints restrict the types that can be used as type parameters. Example:

  • where T : struct - T must be a value type.
  • where T : class - T must be a reference type.
  • where T : new() - T must have a parameterless constructor.

Example:

Key Point: Constraints make generics more flexible and applicable to specific scenarios.

using System;

class Program {
    static void Main() {
        DisplayDefault<int>();
        DisplayDefault<string>();
    }

    static void DisplayDefault<T>() where T : new() {
        T instance = new T();
        Console.WriteLine("Created instance of: " + typeof(T));
    }
}

6

Generic Collections

C# provides several built-in generic collections:

  • List<T>: Stores a collection of elements in a dynamic array.
  • Dictionary<TKey, TValue>: Stores key-value pairs for fast lookups.
  • Queue<T>: Implements a First In, First Out (FIFO) structure.

Example: Using a generic list:

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
        names.Add("Diana");

        foreach (string name in names) {
            Console.WriteLine(name);
        }
    }
}

7

Practice Challenge

Create a generic class Pair<TKey, TValue> that stores a key-value pair and a generic method Swap() that swaps the key and value. Example:

using System;

class Pair<TKey, TValue> {
    public TKey Key { get; set; }
    public TValue Value { get; set; }

    public void Swap() {
        (Key, Value) = ((TKey)(object)Value, (TValue)(object)Key);
    }

    public void Display() {
        Console.WriteLine($"Key: {Key}, Value: {Value}");
    }
}

class Program {
    static void Main() {
        Pair<string, int> pair = new Pair<string, int> { Key = "Age", Value = 30 };
        pair.Display();
        pair.Swap();
        pair.Display();
    }
}

8

9

Best Practices for Using Generics

Here are some best practices:

  • Use generics to create reusable and type-safe classes and methods.
  • Apply constraints when specific type requirements are needed.
  • Prefer generic collections over non-generic ones for performance and safety.

Tip: Use meaningful type parameter names, such as T for type or TKey and TValue for key-value pairs.

10

Great Job!

Congratulations! You’ve learned how to use generics to create reusable and flexible code in C#. In the next lesson, we’ll explore asynchronous programming with async and await. Let’s keep coding!

Generics in C# — illustration 10

Frequently asked questions

Is the “Generics in C#” lesson free?

Yes — the full text of “Generics in C#” is free to read here on the web, and the C# Academy course includes 5 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Generics in C#”?

Learn how generics enable type-safe and reusable code structures. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 5, so you can start here or from the beginning and move at your own pace.

How long does the “Generics in C#” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Generics in C#
  2. Async and Await: Working with Asynchronous Code
  3. Understanding Threading and Tasks
  4. Exploring Delegates and Lambdas
  5. Understanding Reflection in C#
← Back to C# Academy