Generics
Generic Constraints
A generic constraint requires a type parameter to provide certain members.
Generic Constraints
GenericConstraints.cs
using System;
interface INamed
{
string Name { get; }
}
class Customer : INamed
{
public string Name { get; }
public Customer(string name)
{
Name = name;
}
}
class Program
{
static string Label<T>(T item) where T : INamed
{
return "name:" + item.Name;
}
static void Main()
{
string name = ;
Customer customer = new Customer(name);
string label = Label(customer);
Console.WriteLine($"name={name}");
Console.WriteLine($"label={label}");
}
}
using System;
interface INamed
{
string Name { get; }
}
class Customer : INamed
{
public string Name { get; }
public Customer(string name)
{
Name = name;
}
}
class Program
{
static string Label<T>(T item) where T : INamed
{
return "name:" + item.Name;
}
static void Main()
{
string name = ;
Customer customer = new Customer(name);
string label = Label(customer);
Console.WriteLine($"name={name}");
Console.WriteLine($"label={label}");
}
}
using System;
interface INamed
{
string Name { get; }
}
class Customer : INamed
{
public string Name { get; }
public Customer(string name)
{
Name = name;
}
}
class Program
{
static string Label<T>(T item) where T : INamed
{
return "name:" + item.Name;
}
static void Main()
{
string name = ;
Customer customer = new Customer(name);
string label = Label(customer);
Console.WriteLine($"name={name}");
Console.WriteLine($"label={label}");
}
}
constraint
A constraint limits which types can be used with a generic method or class.