Constrained genericity: Difference between revisions

→‎{{header|C#}}: Added C# example
mNo edit summary
(→‎{{header|C#}}: Added C# example)
Line 37:
 
=={{header|C#}}==
 
In C#, type constraints are made on the type hierarchy, so here we make <code>IEatable</code> an interface, with an <code>Eat</code> method. Types which are eatable would have to implement the <code>IEatable</code> interface and provide an <code>Eat</code> method.
 
<lang c#>interface IEatable
{
void Eat();
}</lang>
 
Type constraints in type parameters can be made via the <code>where</code> keyword, which allows us to qualify T. In this case, we indicate that the type argument must be a type that is a subtype of <code>IEatable</code>.
 
<lang C#>using System.Collections.Generic;
 
class FoodBox<T> where T : IEatable
{
List<T> food;
}</lang>
 
For example, an eatable Apple:
 
<lang C#>class Apple : IEatable
{
public void Eat()
{
System.Console.WriteLine("Apple has been eaten");
}
}</lang>
 
C# also has the interesting functionality of being able to require that a generic type have a default constructor. This means that the generic type can actually instantiate the objects without ever knowing the concrete type. To do so, we constrain the where clause with an additional term "new()". This must come after any other constraints. In this example, any type with a default constructor that implements IEatable is allowed.
 
<lang C#>using System.Collections.Generic
 
class FoodMakingBox<T> where T : IEatable, new()
{
List<T> food;
 
void Make(int numberOfFood)
{
this.food = new List<T>();
for (int i = 0; i < numberOfFood; i++)
{
this.food.Add(new T());
}
}
}</lang>
 
=={{header|C++}}==