CodeContracts for specific generic interface

62 views Asked by At

I would like to use CodeContracts for validating some specific implementations of generic interface. I had a basic generic interface

 public interface IEnityMap<in TSource,out TDest>
 {
  TDest Map(TSource);
 }

I want to determine CodeContracts for some specific interfaces. I trying to do something like this:

[ContractClass(typeof(ContractClass))]
public interface ISpecific: IEntityMap<SourceClass,DestClass>{}

[ContractClassFor(typeof(ISpecific))]
public abstract class ContractClass: ISpecific
{
public DestClass Map(SourceClass source)
{
  Contract.Requires(source.SomeProperty!= null);
  //Other checks
  return default(DestClass);
}
}

My Mapping class implements generic interface - IEntityMap<,> (not ISpecific) and this contract does`t work.

1

There are 1 answers

0
Ronald Rink 'd-fens' On

As I understand from your code samples you derive a more specialised interface where you have more constraints in place than in the generic interface. According to the documentation (and the underlying Liskov substiution principle) it is simply not allowed to have more constraints in a subclass or a more specialised interface.

You should get an error like

"... implements interface method ... thus cannot add Requires"

What you could do is to try to cast the types to your specific types and then assert your specific implementation in a derived (abstract) base class. However, having interfaces that behave differently depending on the passed values might be error prone and cause unexpected runtime errors.

Regards, Ronald