Search code examples
c#.net-4.0code-contracts

Code Contracts: how to suppress this "requires unproven" warning?


I have a piece of code for which cccheck tells me that a Requires() is unproven and that I should add a !string.IsNullOrWhitespace(...). That condition is already checked for as I call my own extension method that I have written back in the days of .Net 3.5:

public static bool IsEmpty(this string s)
{
    if (s == null) return true;
    if (s.Length == 0) return true;
    for (int i = 0; i < s.Length; i++)
        if (!char.IsWhitespace(s[i]))
            return false;
    return true;
}

public static bool IsNotEmpty(this string s)
{
    return !IsEmpty(s);
}

My code already requires that value is IsNotEmpty:

Contract.Requires(value.IsNotEmpty(), "The parameter 'value' cannot be null or empty.");

How can I tell cccheck (and the rest of the Code Contracts framework) that IsNotEmpty() already checks for !string.IsNullOrWhitespace(...)?


Solution

  • Try Contract.Ensures(Contract.Result() == !string.IsNullOrWhitespace(s))

    EDIT:

    Yes, I realized this would cause "ensures unproven" when I posted it and I was hoping to find some time to answer more thoroughly. One (somewhat trivial) way to fix it, if you can stand throwing away your old code:

    public static bool IsEmpty(this string s) 
    { 
        Contract.Ensures(Contract.Result() == string.IsNullOrWhitespace(s))
        return string.IsNullOrWhitespace(s);
    } 
    
    public static bool IsNotEmpty(this string s) 
    { 
        Contract.Ensures(Contract.Result() == !string.IsNullOrWhitespace(s))
        return !string.IsNullOrWhitespace(s);
    }