I have defined an abstract class with an abstract constraint :
abstract class Asset<P> where P : Parm { }
abstract class Parm { }
class StockParm : Parm { }
class Stock : Asset<StockParm> { }
class BondParm : Parm { }
class Bond : Asset<BondParm> { }
List<Asset<Parm>> assets = new List<Asset<Parm>>();
Stock stock;
assets.Add(stock);
But I have received the error message:
"Cannot convert type Stock to Asset"
Is there a way to list all the assets?
Thanks
You need to explain to the compiler that Asset<Derived> is Asset<Base>. The compiler compiles generic classes into deperate classes - one for each T. The name of telling the compiler that it is "ok" is covariant.
MSDN:
Covariance - Enables you to use a more derived type than originally specified. You can assign an instance of IEnumerable (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable.
Change Asset<T> to an interface and add the out keyword:
interface Asset<out P> where P : Parm { }
public static class Program
{
public static void Main(string[] args)
{
List<Asset<Parm>> assets = new List<Asset<Parm>>();
Stock stock = new Stock();
assets.Add(stock);
}
}
public abstract class Parm { }
public class StockParm : Parm { }
public interface Asset<out P> where P : Parm { }
public class Stock : Asset<StockParm> { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With