Sobes.tech
Junior — Middle

Kas on piiranguid oma universaalse mallide (üldise) määratlemisel?

sobes.tech AI

Vastus AI-lt

When defining your own universal templates (generics) in C#, there are certain restrictions:

  • Parameter types must be reference types, value types, or have certain constraints (constraints), such as inheriting from a specific class, implementing an interface, or having a parameterless constructor.
  • Primitive types cannot be used directly without constraints if specific functionality is required.
  • You cannot create instances of the parameter type without the new() constraint, as the compiler does not know how to initialize it.
  • The operators typeof(T) or is T cannot be used without constraints.

Example of a constraint:

public class Repository<T> where T : IEntity, new()
{
    public T CreateNew() => new T();
}

Here, T must implement the IEntity interface and have a parameterless constructor.