Mikkel R. Lund
Mikkel R. Lund

Reputation: 2627

Creating a Resharper Naming Style for C# Contract Classes

When writing code contracts on interfaces using Microsoft's Code Contracts, one creates an abstract contract class that contains all the contracts:

using System.Diagnostics.Contracts;

[ContractClass(typeof(ICollectionContract<>))]
public interface ICollection<T> {
    // Interface methods
}

[ContractClassFor(typeof(ICollection<>))]
abstract class ICollectionContract<T> : ICollection<T> {
    // Interface contracts
}

The Microsoft convention is to name the contract class the same as the interface, but with a suffix of Contract, e.g. ICollectionContract<T>. However, Resharper is not a fan of the naming - partly due to the I prefix for an abstract class.

Is there a way to create a naming style that tells Resharper that contract classes (those annotated with ContractClassFor) must have the same name as the interface but with a suffix of Contract?

Upvotes: 2

Views: 171

Answers (1)

Igal Tabachnik
Igal Tabachnik

Reputation: 31548

That's not something you can configure ReSharper to do out of the box, you'd have to create a custom plugin.

You'd have to create an ElementProblemAnalyzer<IInterfaceDeclaration>, then check that it contains the [ContractClass] attribute, and then make sure it has the correct name. You can also create a QuickFix suggestion to rename the interface.

A good start would be something similar to the AsyncSuffix plugin - it has a good implementation that analyzes async methods for a missing Async suffix, offering to add it. Look at that implementation for ideas for your own plugin.

Upvotes: 1

Related Questions