capypad
0 day streak
csharp / intermediate
Snippet

Constraining Type Parameters with Generic Constraints

Generic constraints allow you to restrict the types that can be used as arguments for a type parameter. By using 'where T : class, new()', we ensure that T is a reference type and has a public parameterless constructor.

snippet.csharp
csharp
1
2
3
4
5
6
7
public class Repository<T> where T : class, new()
{
public T CreateInstance()
{
return new T();
}
}
Breakdown
1
where T : class
Ensures that the type parameter T must be a reference type (class, interface, delegate, or array).
2
new()
Specifies that the type T must have a public parameterless constructor, allowing the use of 'new T()'.