Why does a generic type constraint result in a no implicit reference conversion error?

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

C# generic methods, type parameters in new() constructor constraint

Not really; C# only supports no-args constructor constraints. The workaround I use for generic arg constructors is to specify the constructor as a delegate: public T MyGenericMethod<T>(MyClass c, Func<MyClass, T> ctor) { // … T newTObj = ctor(c); // … } then when calling: MyClass c = new MyClass(); MyGenericMethod<OtherClass>(c, co => new OtherClass(co));

C# generic “where constraint” with “any generic type” definition?

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

What do

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

tech