views:

61

answers:

1

I am experimenting with .NET Code Contracts. The following code runs just fine when runtime contract checking is turned off, but fails when runtime contract checking is turned on:

using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace ConsoleApplication1
{
    public class Item<T> where T : class { }
    public class FooItem : Item<FooItem> { }

    [ContractClass(typeof(ITaskContract<>))]
    public interface ITask<T> where T : Item<T>
    {
        void Execute(IEnumerable<T> items);
    }

    [ContractClassFor(typeof(ITask<>))]
    internal abstract class ITaskContract<T> : ITask<T> where T : Item<T>
    {
        void ITask<T>.Execute(IEnumerable<T> items)
        {
            Contract.Requires(items != null);
            Contract.Requires(Contract.ForAll(items, x => x != null));
        }
    }

    public class FooTask : ITask<FooItem>
    {
        public void Execute(IEnumerable<FooItem> items) { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new FooTask();
        }
    }
}

The error I get when running this code is not a contract violation. Rather, it looks like the rewriter is somehow generating a corrupted binary:

Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at ConsoleApplication1.Program.Main(String[] args)

The error goes away if I remove the following line:

Contract.Requires(Contract.ForAll(items, x => x != null));

Am I doing something wrong, or is this a bug in the binary rewriter? What can I do about it?