How to use generics

Generics in programming allow you to define classes, methods, interfaces, or delegates with placeholders for types. These placeholders can be replaced with specific types at runtime, providing type safety while also enabling code reusability. Generics are commonly used in statically typed languages like C#, Java, and TypeScript.

Here’s a breakdown of how to use generics with some examples in C#:

1. Generic Class

You can create a class that can operate on any type, and when you instantiate it, you specify the type you want it to work with.

 

// Define a generic class with a type placeholder T
public class Box<T>
{
    private T item;

    public void Add(T newItem)
    {
        item = newItem;
    }

    public T Get()
    {
        return item;
    }
}

// Usage
var intBox = new Box<int>();
intBox.Add(123);
Console.WriteLine(intBox.Get());  // Output: 123

var stringBox = new Box<string>();
stringBox.Add("Hello");
Console.WriteLine(stringBox.Get());  // Output: Hello

 

Up Next
    Ebook Download
    View all
    Learn
    View all