I like to separate my definitions from my implementations. I have an interface Entity:
public interface Entity<E> where E : Entity<E>
{
EntityId EntityId { get; }
bool ReadOnly { get; }
void FailIfReadOnly();
E Copy();
}
E is the actual entity type, such as Customer:
public interface Customer : Entity<Customer>
{
}
The problem I have is the implementation of FailIfReadOnly(): if ReadOnly == true, then throw an EntityIsReadOnlyException.
public class EntityIsReadOnlyException<E> where E : Entity<E>
{
public EntityIsReadOnlyException(E entity)
: base(string.Format("Entity {0} is read only", entity.EntityId))
{
}
}
public class EntityImpl<E> : Entity<E> where E : Entity<E>
{
public EntityImpl(E other)
{
}
public bool ReadOnly
{
get;
protected set;
}
public void FailIfReadOnly()
{
if (! ReadOnly) throw new EntityIsReadOnlyException<E>(this);
}
}
The throw new EntityIsReadOnlyException<E>(this);
causes a compilation error:
The best overloaded method match for 'EntityIsReadOnlyException.EntityIsReadOnlyException(E)' has some invalid arguments
Argument '1': cannot convert from 'EntityImpl' to 'E'
I can do:
EntityIsReadOnlyExcetion<Customer> exc = new EntityIsReadOnlyException<Customer>(customerImpl);
and even:
Entity<E> entity = new EntityImpl<E>(this);
but not:
EntityIsReadOnlyException<E> exc = new EntityIsReadOnlyException<E>(this);
In both cases, E is restricted to subclasses of Entity. My question is, why do I get this compilation error? It's probably something very simple.