简体   繁体   中英

About c# Contract classes and nested types in interfaces

I am looking for contract classes that I see some code examples. I wonder what is it. So there is a sample code like this.

[ContractClass(typeof(ICaseConverterContracts))] 
public interface ICaseConverter 
{ 
    string Convert(string text); 
}
[ContractClassFor(typeof(ICaseConverter))] 
internal class ICaseConverterContracts : ICaseConverter 
{ 
    string ICaseConverter.Convert(string text) 
    { 
        Contract.Requires(text != null); 
        Contract.Ensures(Contract.Result<string>() != null); 
        return default(string); 
    }

    private ICaseConverterContracts() {} 
}

public class InvariantUpperCaseFormatter : ICaseConverter 
{ 
    public string Convert(string text)  
    { 
        return text.ToUpperInvariant(); 
    } 
}

What does contracts here?

I have created a new instance of InvariantUpperCaseFormatter.

class Program
{
    static void Main(string[] args)
    {
        InvariantUpperCaseFormatter formatter = new InvariantUpperCaseFormatter();
        Console.Write(formatter.Convert(string.Empty));
    }
}

and I put the breakpoint to method ICaseConverter.Convert(string text) in ICaseConverterContracts class but it does not break. what does it? Automatically check if name is not null?

The code you see is a piece of code that utilizes Code contracts (here) (and here) . Some of the facilities provided by code contracts are usable by default but others rely on the IL rewriter that modifies your code when you build it. So until you install code contracts and activate it by directive some code won't be used.

I suppose that your question is a little bit too broad. If you're interested surf the links I provided above. The contract in the code you posted checks two things: first, it checks that the input is not null , then it checks the output for also not being null .

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