Junior — Middle
Can you explain the concept of generic types in programming?
sobes.tech AI
Answer from AI
Generic types in programming allow creating classes, methods, or interfaces that work with different data types without losing type safety.
In C#, this is implemented using type parameters, for example:
public class Box<T>
{
private T _value;
public void SetValue(T value)
{
_value = value;
}
public T GetValue()
{
return _value;
}
}
// Usage:
var intBox = new Box<int>();
intBox.SetValue(123);
var stringBox = new Box<string>();
stringBox.SetValue("Example");
This approach allows writing universal code that works with any types, avoiding duplication and casting errors.