Skip to content

where T IMyInterface (interface constraint)

Context: The constraint where T : IMyInterface requires the type parameter to implement the specified interface. This allows calling the interface members on instances of T. Multiple interfaces can be combined.

using System;
using System.Collections.Generic;
public interface IIdentifiable
{
int Id { get; }
string Name { get; }
}
public class Product : IIdentifiable
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Customer : IIdentifiable
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Display<T> where T : IIdentifiable
{
public void ShowIdentity(T item)
{
Console.WriteLine($"ID: {item.Id}, Name: {item.Name}");
}
}
class Program
{
static void Main()
{
var product = new Product { Id = 1, Name = "Laptop" };
var customer = new Customer { Id = 100, Name = "Alice" };
var display = new Display<IIdentifiable>();
display.ShowIdentity(product);
display.ShowIdentity(customer);
}
}
Terminal window
dotnet run
ID: 1, Name: Laptop
ID: 100, Name: Alice
  • You can impose multiple interfaces: where T : IInterface1, IInterface2.
  • The interface can be generic itself.

List<T> – Does not impose an interface, but Dictionary<TKey, TValue> indirectly uses IEquatable<TKey>.
See .NET docs on interface constraint.