Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code contracts doesn't check null condition. Why?

Why doesn't Contracts for .NET complain about this code ?

private static User GetUser()
{
    var sFirstName = Console.ReadLine();
    var sLastName = Console.ReadLine();
    if (sLastName == "NULL")
    {
        return null;
    }
    else
    {
        return new User(sLastName, sFirstName);
    }
}
public static int Main(string[] args)
{
        var oUser = GetUser();
        DisplayUser(oUser);
        Console.ReadLine();
        return 0;
}
private static void DisplayUser(User user)
{
    Contract.Requires(user != null);
    Console.WriteLine(user.ToString());
}

GetUser can return null, but contract never says that I must check the return value before passing it to DisplayUser. Why?


AutoAnswer: There is a Warning Level in Code Contracts config. I should have put it from low to hi.

like image 840
user1485585 Avatar asked May 07 '26 04:05

user1485585


1 Answers

According to this msdn page, the contracts will not be enforced if you do not have the proper plugin installed in Visual Studio. Have you installed that plugin?

You must install a Visual Studio add-in to enforce contracts. The Code Contracts Premium Edition add-in lets you specify static and run-time checking of code contracts on the project Properties page. If you do not enable run-time checking, contracts such as the Contract.Ensures method will not throw exceptions during run time if a contract is violated. The Visual Studio add-in does not ship with Visual Studio 2010 or the Windows SDK.

like image 87
Øyvind Bråthen Avatar answered May 08 '26 19:05

Øyvind Bråthen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!