csharp / intermediate
Snippet
Restricting Generic Types with Specific Constraints
Generic constraints allow you to limit which types can be used as arguments for a generic class or method. This ensures that the type has certain capabilities, such as being a reference type, having a parameterless constructor, or implementing a specific interface.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Repository<T> where T : class, new(){public T CreateDefault(){// Valid because of 'new()' constraintreturn new T();}public void Reset(T entity) where T : IDisposable{entity.Dispose();}}
Breakdown
1
where T : class, new()
Ensures T must be a reference type and must have a public parameterless constructor.
2
where T : IDisposable
Applies a constraint to a specific method, requiring T to implement IDisposable.