Search code examples
c#coding-stylenested-classcode-organizationiequalitycomparer

What's a good place to put Comparers?


EqualityComparer<T>...where should it go? Nested in the class it's comparing? Or in it's own file? Or in a file with all the other custom Comparers?

Are there generally agreed upon coding guidelines, and what do they suggest in this case?


Solution

  • While some conventions do change over time, the .NET 1.1 C# coding conventions available on MSDN are a pretty good place to start.

    Regarding nested classes:

    Do not use nested types if … [the] type must be instantiated by client code. If a type has a public constructor, it probably should not be nested. The rationale behind this guideline is that if a nested type can be instantiated, it indicates that the type has a place in the library on its own. You can create it, use it, and destroy it without using the outer type. Therefore, it should not be nested. An inner type should not be widely reused outside of the outer type without a relationship to the outer type.

    Regarding organization of C# source code files, it's common practice to place each class in a separate .cs file, with the same name as the class. This makes it easy to find the class when you're browsing the repository, and generally helps in understanding the organization of the code at a glance. This has been discussed on SO as well.

    This rule is not as strongly enforced, and I've seen a number of people stray from it in particular situations. However, unless you really have a specific need to keep the classes together, I'd recommend a separate .cs file for each.

    So summing up. If you have a main class Foo and a comparer, FooComparer, you would have a separate class file for each, Foo.cs and FooComparer.cs