Restricciones genéricas — RexDac Academy

RexDac AcademyNotas técnicas · Ayuda tener algunos conocimientos previos
0%Notas publicadas leídas · en este dispositivo

Nivel 6 — Genéricos y delegados

Restricciones genéricas

Notas originales de SunDiaL · Ver fuente en inglés

Puedes restringir los tipos que puede admitir un genérico mediante restricciones. Algunas restricciones habituales son:

  • where T : class – T debe ser un tipo de referencia.
  • where T : struct – T debe ser un tipo de valor.
  • where T : new() – T debe tener un constructor público sin parámetros.
  • where T : BaseClass – T debe heredar de una clase base concreta.
  • where T : Interface – T debe implementar una interfaz concreta.
  • where T : unmanaged – T debe ser un tipo no administrado, como int, float, etc.

Ejemplo

public class Printer<T> where T : class
{
	public void Print(T item)
	{
		if (item == null)
		{
			Console.WriteLine("Nothing to print.");
			return;
		}
		Console.WriteLine(item.ToString());
	}
}

public void Main()
{
	Printer<string> p1 = new Printer<string>();
	p1.Print("Hello");      // prints "Hello"
	p1.Print(null);         // prints "Nothing to print"
	
	Printer<int> p2 = new Printer<int>(); // compile-time error: int is not a class
}