Problem using Lazy<T> from within a generic abstract class
        Posted  
        
            by James Black
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by James Black
        
        
        
        Published on 2010-05-20T18:03:50Z
        Indexed on 
            2010/05/21
            9:30 UTC
        
        
        Read the original article
        Hit count: 344
        
c#4.0
|generic-variance
I have a generic class that all my DAO classes derive from, which is defined below. I also have a base class for all my entities, but that is not generic.
The method GetIdOrSave is going to be a different type than how I defined SabaAbstractDAO, as I am trying to get the primary key to fulfill the foreign key relationships, so this function goes out to either get the primary key or save the entity and then get the primary key. 
The last code snippet has a solution on how it will work if I get rid of the generic part, so I think this can be solved by using variance, but I can't figure out how to write an interface that will compile.
public abstract class  SabaAbstractDAO<T>
    {
      ...
    public K GetIdOrSave<K>(K item, Lazy<SabaAbstractDAO<BaseModel>> lazyitemdao) where K : BaseModel
    {
        if (item != null && item.Id.IsNull())
        {
            var itemdao = lazyitemdao.Value;
            item.Id = itemdao.retrieveID(item);
            if (item.Id.IsNull())
            {
                return itemdao.SaveData(item);
            }
        }
        return item;
    }
}
I am getting this error, when I try to compile:
 Argument 2: cannot convert from 'System.Lazy<ORNL.HRD.LMS.Dao.SabaCourseDAO>' to 'System.Lazy<ORNL.HRD.LMS.Dao.SabaAbstractDAO<ORNL.HRD.LMS.Models.BaseModel>>'
I am trying to call it this way:
        GetIdOrSave(input.OfferingTemplate,
            new Lazy<SabaCourseDAO>(
                () =>
                {
                    return new SabaCourseDAO() { Dao = Dao };
                })
        );
If I change the definition to this, it works.
    public K GetIdOrSave<K>(K item, Lazy<SabaCourseDAO> lazyitemdao) where K : BaseModel
    {
So, how can I get this to compile using variance (if needed) and generics, so I can have a very general method that will only work with BaseModel and AbstractDAO<BaseModel>? I expect I should only need to make the change in the method and perhaps abstract class definition, the usage should be fine.
© Stack Overflow or respective owner