none
string.Format and string.IsNullOrEmpty

    Question

  • Given this code:

    public static void ErrorAndThrow(string message, Exception exception)
    {
        Contract.Requires(!string.IsNullOrEmpty(message));
        Contract.Requires(exception != null);
    
        Error(message, exception);
        throw exception;
    }
    And this call:

    public static string ReturnAttributeValueOrThrow(this XElement xmlElement, string attributeName)
    {
        Contract.Requires(xmlElement != null);
        Contract.Requires(!string.IsNullOrEmpty(attributeName));
    
        XAttribute element = xmlElement.Attribute(attributeName);
    
        if (element == null || string.IsNullOrEmpty(element.Value))
            Logger.ErrorAndThrow(string.Format(CultureInfo.CurrentCulture, "Null attribute '{0}' or empty value", attributeName), new InvalidXmlException());
    
        return element.Value;
    }
    Why does this line:

    Logger.ErrorAndThrow(string.Format(CultureInfo.CurrentCulture, "Null attribute '{0}' or empty value", attributeName), new InvalidXmlException());
    generate this warning?

    Warning 14 CodeContracts: requires unproven: !string.IsNullOrEmpty(message)

    Obsiously string.Format can't return a null or empty string in this case, as there is a pre condition on attributeName.

    Or maybe I'm wrong?
    Friday, March 05, 2010 4:17 PM

Answers

  • Hi,

    Just to be clear on my last point, the problem is exactly as Eric pointed out: string.Format does not ensure a non-empty return value.  But I believe that the reason why it can't is because CC doesn't reason about the contents of strings; e.g., format could be specified as "{0}" with a single argument that is string.Empty, but the static checker isn't able to prove that this call returns string.Empty while others may not.

    - Dave
    http://davesexton.com/blog
    Sunday, March 07, 2010 9:17 PM

All replies