简体   繁体   中英

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(...) ?

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);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM