Junior — Middle
Can you explain what is meant by generic types in programming?
sobes.tech AI
Answer from AI
Generics in programming allow creating classes, methods, or structures that work with different data types while maintaining type safety.
This means you can write one universal code that works with any type, for example, a list of elements of any type, without needing to write separate code for each type.
Example in C#:
public class GenericList<T>
{
private T[] items;
private int count;
public void Add(T item) {
// add item
}
public T Get(int index) {
return items[index];
}
}
// Usage:
var intList = new GenericList<int>();
intList.Add(5);
var stringList = new GenericList<string>();
stringList.Add("text");
Here, T is a type parameter that is replaced with a specific type when creating an instance.