7

I'm using Microsoft's Code Contracts extension with C#. When I write a class with an overridden ToString implementation that returns null, it correctly identifies the issue:

CodeContracts string cannot be null

I assumed this was because Microsoft uses Code Contracts internally, and they added a Contract.Ensures call to Object.ToString. However, when I look at the Object.ToString source code I don't see any contracts (I do see other contracts, but not the one I'm looking for). How does Code Contracts determine that ToString shouldn't return null?

Will
  • 2,086
  • 23
  • 30

1 Answers1

6

This is the Code Contracts internal definition of System.Object: (link). As you can see, they've defined ToString() with this constraint:

Contract.Ensures(Contract.Result<string>() != null);

To answer your question, Code Contracts knows it's not null because of an internal contract definition.

  • 1
    To provide a bit more information: The Code Contracts are not in the official assemblies, therefore you don't see them on referencesource.microsoft.com. The Code Contracts team defined all Code Contracts themselves and provide them in seperate contract reference assemblies, which only contain contracts and not real source. – cremor Oct 27 '15 at 06:44
  • @cremor Thanks! Just FYI, I do see a lot of contracts on ReferenceSource (e.g. in [Object.cs](http://referencesource.microsoft.com/#mscorlib/system/object.cs,180)) but I guess that the contracts could be specified in either .NET core or in Code Contracts, depending on who wrote them. – Will Oct 27 '15 at 08:16