Sobes.tech
Middle

What are generic types (Generics)?

sobes.tech AI

Answer from AI

Generics allow defining classes, interfaces, and methods using type parameters. This increases flexibility, reusability, and type safety of the code, enabling working with different data types without losing static type checking.

Key advantages:

  • Type safety: The compiler checks types at compile time, preventing runtime errors related to type mismatches.
  • Reusability: The same code can be used with different data types, reducing code duplication.
  • Performance: In some languages (e.g., C#), generics are implemented considering the specific type, which can improve performance compared to using Object.

Examples of usage:

  • Collections: Lists, dictionaries, sets parameterized by element type.
  • Methods: Methods working with any data type implementing a specific interface.
  • Classes: Wrapper classes, factories working with type parameters.

Example in C#:

// Generic list
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");

// Generic method
public T GetFirstElement<T>(List<T> list)
{
    if (list != null && list.Count > 0)
    {
        return list[0];
    }
    return default(T); // Returns default value for type T
}

Example in Java:

// Generic list
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

// Generic method
public <T> T getFirstElement(List<T> list) {
    if (list != null && !list.isEmpty()) {
        return list.get(0);
    }
    return null; // Returns null for reference types
}

Example in Python (type hinting):

from typing import List, TypeVar

T = TypeVar('T')

def get_first_element(data: List[T]) -> T | None:
    # Function can work with any list and return an element from it
    if data:
        return data[0]
    return None

names: List[str] = ["Alice", "Bob"]
first_name = get_first_element(names) # IDE understands that first_name is str

In some languages (Java), generics use "type erasure," where information about the type parameter is removed at compile time. This can lead to some limitations. In other languages (C#, Go), type information is preserved at runtime.

Generics are a fundamental tool for writing clean, safe, and reusable code.