Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Upcast with generics

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

like image 375
user1281273 Avatar asked May 16 '26 03:05

user1281273


1 Answers

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> { }
like image 70
Gilad Green Avatar answered May 18 '26 17:05

Gilad Green