Search code examples
.net-4.0code-contractsccrewrite

CodeContracts: ccrewrite fails with Object reference not set to an instance of an object


The below code makes ccrewrite blow up! Ideas? BTW, If you comment out the ActualClass, ccrewrite succeeds...

    [ContractClass(typeof(TestContracts))]
    interface ITestInterface
    {
        bool IsStarted { get; set; }
        void Begin();
    }

    class ActualClass : ITestInterface
    {
        public bool IsStarted { get; set; }
        public void Begin()
        {
            this.IsStarted = true;
        }
    }

    [ContractClassFor(typeof(ITestInterface))]
    class TestContracts : ITestInterface
    {
        ITestInterface Current { get; set; }

        private TestContracts()
        {
            Current = this;
        }

        #region ITestInterface Members

        bool ITestInterface.IsStarted
        {
            get; set;
        }

        void ITestInterface.Begin()
        {
            Contract.Requires(!Current.IsStarted);
            Contract.Ensures(Current.IsStarted);
        }

Thanks in advance!


Solution

  • Well, serves me right for not reading Jon Skeet well enough ;) The bit about how rewriter takes the contracts and puts them in your actual class...

       [ContractClassFor(typeof(ITestInterface))] 
        class TestContracts : ITestInterface 
        { 
    
            private TestContracts() 
            { 
            } 
    
            #region ITestInterface Members 
    
            bool ITestInterface.IsStarted 
            { 
                get; set; 
            } 
    
            void ITestInterface.Begin() 
            { 
                ITestInterface iface = this;
                Contract.Requires(!iface.IsStarted); 
                Contract.Ensures(iface.IsStarted); 
            } 
        }
    

    http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/853227bf-56e6-427b-8e9e-162c129e87ce/