3
votes

I have an MVVM project in C#, and I want to use code contracts in it. So this is my scenario: Interface:

public interface IC042_Model
{
    void Save(C042 entity);
    void Delete(C042 entity);
}

Then I have the abstract class for the contracts:

[ContractClassFor(typeof(IC042_Model))]
internal abstract class C042_Model_Contracts : IC042_Model
{
    public void Save(C042 entity)
    {
        Contract.Requires(entity != null);
    }

    public void Delete(C042_CondicaoPagamento entity)
    {
        Contract.Requires(entity != null);
    }
}

In another project, my model implements the interface, and if I call this.Save(null) in any method, an warning is generated. In my ViewModel, if I call the same method above: this.Save(null), no warning is generated, but when I run the application the above line raises a Contract exception.

Is there anything wrong with my approach?

Thanks in advance.

I've made another example that I think it will be easier for everyone to understand:

I've created the following class in a class library project:

public static class StringExtensions
{
    public static string TrimAfter(string value, string suffix)
    {
        Contract.Requires(suffix != (string)null);
        Contract.Requires(!string.IsNullOrEmpty(suffix));
        Contract.Requires(value != null);

        var index = value.IndexOf(suffix);

        if (index < 0)
            return value;

        return value.Substring(0, index);
    }
}

When I call it from a WPF project like below:

CodeDigging.StringExtensions.TrimAfter(null, null);

I don't get a warning for the contracts not being fullfield.

That's my problem, I hope it gets clearer now.

Thanks.

1
Can you make your question more specific? - Robert Harvey
What is the specific warning you are receiving? - EtherDragon
Sorry, I wasn't very clear. My problem is that the static checking is not working when I call this.Save(null) in the ViewModel, just in the Model. - Diego Modolo Ribeiro
I copied from a code with much more stuff, so I've changed a few things to turn it more readable, where one reads c042 it should be entity. - Diego Modolo Ribeiro
How does the implementation of the class look like? Do you override Save and Delete? You might have to declare them virtual in your abstract base class. Or why is C042_Model_Contracts abstract after all? - slfan

1 Answers

1
votes

I think you missed the ContractClass attribute on the interface:

[ContractClass(typeof(C042_Model_Contracts)]
public interface IC042_Model 
{ 
    void Save(C042 entity); 
    void Delete(C042 entity); 
} 

There is a good description about code contracts here