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.
Usage Example
Section titled “Usage Example”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); }}Output console
Section titled “Output console”dotnet runID: 1, Name: LaptopID: 100, Name: AliceImportant notes
Section titled “Important notes”- You can impose multiple interfaces:
where T : IInterface1, IInterface2. - The interface can be generic itself.
Real-world usage example
Section titled “Real-world usage example”List<T> – Does not impose an interface, but Dictionary<TKey, TValue> indirectly uses IEquatable<TKey>.
See .NET docs on interface constraint.