What is a practical usage of Code Contracts in .NET 4.0?

后端 未结 4 1819
生来不讨喜
生来不讨喜 2021-02-03 20:01

In order to fully understand and take advantage of the new features and enhancements provided with the coming of the new .NET Framework 4.0, I would like to get an example of

4条回答
  •  滥情空心
    2021-02-03 20:20

    Have you ever seen a NullReferenceException and wished that the compiler could have warned you about it at compile time to avoid finding out the hard way - with your program crashing?

    With code contracts you can write things like:

    Contract.Requires(foo != null);
    

    This isn't just a runtime check - you can set it up so that if you call this function with an argument that might be null you will get a compile error.

    Here's a real world example:

    Address GetAddress(Customer customer)
    {
        Contract.Requires(customer != null, "customer");
        return addressBook.FindCustomer(customer);
    }
    

提交回复
热议问题