Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Contracts and MVVM

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.

like image 899
Diego Modolo Ribeiro Avatar asked Aug 05 '26 10:08

Diego Modolo Ribeiro


1 Answers

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

like image 98
slfan Avatar answered Aug 08 '26 00:08

slfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!