Search code examples
c#roslyncontracts

Code Contracts vs Code Analyzers


I'm about to embark on a new C# project. I was wondering what the difference is between using Code Contracts or Code Analyzers (in Roslyn). Am I misunderstanding the usage of each? Being a new project, I would like to maintain the integrity of the code. So I want other developers to adhere to specific code guidelines. I'll research each further, but I was wanting to get the opinion of the community first. Excuse the question, I'm still rather new to C# development.


Solution

  • They are two different tools.

    Code Contracts is a way to declare and check... well, contracts, such as pre-conditions and post-conditions:

    public class Foo
    {
        public Foo(object arg)
        {
            Contract.Requires<ArgumentNullException>(arg != null);
        }
    
        public object GetBar()
        {
            Contract.Ensures(Contract.Result<object>() != null);
    
            // TODO:
        }
    }
    

    CC check their conditions at run-time. This requires your assembly (not source code!) to be rewritten after compilation to inject appropriate calls into your code.

    Code Analyzers use Roslyn to analyze source code while you're writing it. They can help you to format code, to remind you to call Dispose on IDisposable, and so on, but they don't affect run-time behavior directly.

    There are a number of analyzers, grouped by purpose into projects (like StyleCopAnalyzers), while Code Contracts is a standalone project.

    (CC also have static analyzer, but I can't tell much here - it kills performance when used on real projects, so, for me it is usually turned off. Anyway, it is intended to check contracts.)