Home > Software engineering >  I can't assign value to a generic variable with same type
I can't assign value to a generic variable with same type

Time:10-07

I have created a generic class with 2 type parameters but I can't assign a value to the List principalList that have the same type. _D_Data.GetGrupoProductoList() returns a List<E_grupo_producto>

public class N_TablaSolaBase<TPrincipalInfo, TData>
    where TPrincipalInfo : E_grupo_producto, new()
    where TData : D_Producto, new()
{
    private TPrincipalInfo principalInfo= new TPrincipalInfo();
    private List<TPrincipalInfo> principalList = new List<TPrincipalInfo>();
    private TData _D_Data = new();

    public List<TPrincipalInfo> GetPrincipalList()
    {
        var lista = _D_Data.GetGrupoProductoList();

        MessageBox.Show((lista.GetType() == principalList.GetType()).ToString());
        // show true
        principalList = lista 
        // Can't convert List<E_grupo_producto> to List<TPrincipalInfo>
        return principalList;
    }

CodePudding user response:

You have a variance problem.

If you have; class Animal, class Dog : Animal & class Cat : Animal. Then a List<Animal> can store and retrieve any animal. But if the caller is expecting a List<Dog>, then you can't give them a List<Animal> as there might be a Cat in it. But also, if the caller has asked for a List<Animal>, you can't give them a List<Dog> as the caller might try to put a Cat in it.

Your class N_TablaSolaBase<TPrincipalInfo> allows the caller to specify if they want a List<E_grupo_producto> or only a List<OtherProduct> for some class OtherProduct : E_grupo_producto. If they've asked for only List<OtherProduct>, you can't give them a List<E_grupo_producto>.

You could add a runtime cast to return the list if the types actually match. But then why have the generic parameter if the only supported value is E_grupo_producto?

var lista = _D_Data.GetGrupoProductoList() as List<TPrincipalInfo>
    ?? throw new NotSupportedException();

Or you could change your D_Producto class to add a generic parameter, to ensure that GetGrupoProductoList returns a List<TPrincipalInfo>.

public class N_TablaSolaBase<TPrincipalInfo, TData>
    where TPrincipalInfo : E_grupo_producto, new()
    where TData : D_Producto<TPrincipalInfo>, new() {...}

public class D_Producto<TPrincipalInfo>
    where TPrincipalInfo : E_grupo_producto, new() {
    public List<TPrincipalInfo> GetGrupoProductoList() {...}
}
  • Related