Sobes.tech
Junior — Middle

Why are universal data types used in programming?

sobes.tech AI

Answer from AI

Universal data types (generics) in programming allow creating classes, methods, and structures that work with any data types, ensuring type safety and code reuse.

Advantages:

  • Code reuse: You can write one method or class that works with different types.
  • Type safety: Type errors are detected at compile time rather than at runtime.
  • Performance: Avoids boxing and unboxing of types.

Example in C#:

public class Stack<T>
{
    private T[] elements;
    private int position = 0;

    public Stack(int size) {
        elements = new T[size];
    }

    public void Push(T item) {
        elements[position++] = item;
    }

    public T Pop() {
        return elements[--position];
    }
}

Here, Stack<T> can be a stack for any data type.