C# Interview Question #31

What are generics in C#?

Generics & Collections Mid-Level Intermediate

Quick Interview Answer

Generics allow classes, interfaces, methods, delegates, and other types to operate with type parameters instead of being written for one specific data type.

Detailed Explanation

Generics allow classes, interfaces, methods, delegates, and other types to operate with type parameters instead of being written for one specific data type.

Generics improve type safety, code reuse, and often performance because they avoid unnecessary casting and can avoid boxing for value types.

Common .NET generic types include List<T>, Dictionary<TKey,TValue>, IEnumerable<T>, Task<T>, and Nullable<T>.

Code Example

public T GetFirst<T>(IEnumerable<T> items)
{
    return items.First();
}

int first = GetFirst(new[] { 10, 20, 30 });