4

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • I am running this on a 32-bit x86 machine. I have tried setting the platform target in the build configuration to both 'x86' and 'Any CPU', but I get the same result either way. I have not tried to run this on an x64 machine. – Jim Killingsworth Aug 26 '10 at 02:45
  • 1
    I see same result. Win7 Prof 64bit + VS 2010 Ultimate, Code Contracts 1.4.30707.2. It is still in dev phase, so it will have some bugs. – Tomas Voracek Aug 26 '10 at 20:37
  • 1
    I would recommend you report this on the CC forum, here: http://social.msdn.microsoft.com/Forums/en/codecontracts/threads – porges Aug 26 '10 at 21:27

1 Answers1