Generics and typecasting

public class ObjectA{
    //..
}

public class ObjectB: ObjectA{
    //..
}

public abstract class ObjectAList<T>: List<T> where  T:  ObjectA {
    //..
    public void LoadData(ObjectAList aList){
       XYZ.Load(aList);
    }
}

public class ObjectBList: ObjectAList<ObjectB> {
    private _fObjectBList = new ObjectBList();
    public void AfterCreate(){
       LoadData(fObjectBList)
    } 
}

but this doesnt work it is complaining something like can not convert ObjectB to ObjectA

 

Error 2 Argument '1': cannot convert from ObjectB' to 'ObjectAList<ObjectA>' ...



Answer this question

Generics and typecasting

  • msheridan

    Hi,

    The code you have posted does not compile. Please post the correct code.

    Cheers,

    Nasha.

    from eeks to geeks ......

    you can catch me @ nam_shahathotmail.com or namratha1athotmail.com



  • johncharle

    This code is exactly what I mean/ want to do can anyoine help me out
    using System;
    using System.Collections.Generic;
    using System.Text;

    namespace ConsoleApplication1 {
    class ObjectA {

    }

    class ObjectB: ObjectA {

    }

    class ObjectAList<T>: List<T> where T: ObjectA {
    protected void SomeFunction(ObjectAList<ObjectA> aList) {
    //Do something here withe the list
    }
    }

    class ObjectBList: ObjectAList<ObjectB> {
    private ObjectBList myList = new ObjectBList();

    public void DoSomething() {
    SomeFunction(myList);
    }
    }




    class Program {
    static void Main(string[] args) {

    }
    }
    }


  • Flavio Roberto

    I loaded the code into Snippet Compiler, and it looks like you'll need/want to change your SomeFunction method signature to:


    protected void SomeFunction(ObjectAList<T> aList)


  • Generics and typecasting