I have a situation that is confusing me and was hoping for some help. In the code below the FindById method works without having to cast the return but the UpdatedAuditedEntity call doesn’t. Note that:
- AuditedEntity derives from Entity
- Casting auditedEntity to an Entity doesn’t work, only casting to T works.
Any insight into what I’m missing here would be greatly appreciated. At first I thought it had to do with variance but as I mentioned above I tried down casting with no sucess.
public class NHibernateRepository<T> : NHibernateBase,
IRepository<T> where T : Entity
{
public IEnumerable<T> FindAll(Expression<Func<T, bool>> predicate)
{
var query = GetQuery(predicate);
return Transact(() => query.ToList());
}
public T FindById(int id)
{
// TODO: Why does this work when below doesn't
return FindAll(e => e.Id == id).FirstOrDefault();
}
private T UpdateAuditedEntity(T item)
{
var auditedEntity = item as AuditedEntity;
if (auditedEntity == null) return item;
auditedEntity.DateModified = DateTime.UtcNow;
// TODO: figure out why this cast is necessary
return auditedEntity as T;
}
OK, but in this generic class,
Tis of an arbitrary derivative ofEntity. The compiler doesn’t care that yourauditedEntitywas created by castingitem– indeed, there could be custom conversions at play here doing unexpected things – so doesn’t allow you to return a variable typed asAuditedEntityfrom a method that asks for aT.In this particular method, since
itemandauditedEntityare the same object, you can just doas the last statement of
UpdateAuditedEntityand the compiler will be happy.