How do I specify multiple constraints on a generic type in C#?
public class Animal<SpeciesType,OrderType> where SpeciesType : Species where OrderType : Order { }
public class Animal<SpeciesType,OrderType> where SpeciesType : Species where OrderType : Order { }
Let’s simplify: interface IAnimal { … } interface ICage<T> where T : IAnimal { void Enclose(T animal); } class Tiger : IAnimal { … } class Fish : IAnimal { … } class Cage<T> : ICage<T> where T : IAnimal { … } ICage<IAnimal> cage = new Cage<Tiger>(); Your question is: why is the last … Read more
You can use this to limit it to value types: where C: struct You also mention string. Unfortunately, strings won’t be allowed as they are not value types.
There are typically 2 ways to achieve this. Option1: Add another parameter to IGarrage representing the T which should be passed into the IGenericCar<T> constraint: interface IGarrage<TCar,TOther> where TCar : IGenericCar<TOther> { … } Option2: Define a base interface for IGenericCar<T> which is not generic and constrain against that interface interface IGenericCar { … } … Read more
These are called generalized type constraints. They allow you, from within a type-parameterized class or trait, to further constrain one of its type parameters. Here’s an example: case class Foo[A](a:A) { // ‘A’ can be substituted with any type // getStringLength can only be used if this is a Foo[String] def getStringLength(implicit evidence: A =:= … Read more
That is a constraint on the generic parameter T. It must be a class (reference type) and must have a public parameter-less default constructor. That means T can’t be an int, float, double, DateTime or any other struct (value type). It could be a string, or any other custom reference type, as long as it … Read more