Junior — Middle
How can you impose a restriction on the type of a parameter in a generic?
sobes.tech AI
Answer from AI
In C#, the type parameter constraint in generics is specified using the keyword where. It allows you to specify that the type parameter must inherit from a certain class, implement an interface, be a reference or value type, have a parameterless constructor, etc.
Example:
// Constraint: T must be a class, implement IDisposable, and have a parameterless constructor
public class MyClass<T> where T : class, IDisposable, new()
{
public T CreateInstance()
{
return new T();
}
}
Thus, the compiler guarantees that when using MyClass with a specific type T, it satisfies the specified constraints.