Sobes.tech
Junior — Middle

Can you explain what generic types are in programming?

sobes.tech AI

Answer from AI

Generics (parametric types) allow creating classes, methods, or interfaces that work with different data types while maintaining type safety.

This means you can write a single universal code that works with any type without resorting to type casting and without losing type checking during compilation.

Example in C#:

public class GenericList<T>
{
    private T[] items;
    private int count;

    public void Add(T item)
    {
        // Add element
    }

    public T Get(int index)
    {
        return items[index];
    }
}

// Usage:
var intList = new GenericList<int>();
intList.Add(5);

var stringList = new GenericList<string>();
stringList.Add("Example");

Thus, generics increase code reusability and reduce errors related to incorrect types.

Can you explain what generic types are in… - sobes.tech