Code Contracts Alert to Possible Call Failure

In my class, I have a private type field ExpandoObject. The field is initialized in constructor ( this.expected = new ExpandoObject()), so I'm sure it will never be null.

Thus, in one of the methods of this class, I added with confidence

Contract.Assumes(this.expected != null)

before using this.expectedfor anything, so in Code Contracts you don’t have to worry about possible calls to null objects. However, instead of a warning about a possible method call for a null reference, I get a warning:

A dynamically sent call to the Suppose method may fail at runtime because one or more applicable overloads are conditional methods

The signature of the method and the first few lines of code are as follows:

protected void Expect(object values)
{
    Contract.Requires<ArgumentNullException>(values != null);

    Contract.Assume(this.expected != null);
    var exp = (ICollection<KeyValuePair<string, object>>)this.expected;

In the third line, I get a warning for

CodeContracts: possibly calling the method at the null reference 'OddEnds.Testing.TestBase.o_SiteContainer0. <> p_Site3.Target '

where I assume that the odd signature of the null reference is what expis a dynamic object.

How can I solve these problems?

+3
source share
2 answers

I think the best way to solve your problem is to declare that it is expectednever null as an invariant in the class:

class TheClass {

    ExpandoObject expected;

    ...

    [ContractInvariantMethod]
    void Invariants()
    {
        Contract.Invariant(this.expected != null);
    }

    ...

}

, , expected , , expected .

+4

, ( , expandoobject .. )

ICollection<KeyValuePair<string, object>> col = this.expected as ICollection<KeyValuePair<string, object>>;
Contract.Assume(col != null);
0

Source: https://habr.com/ru/post/1796421/


All Articles