How to name C# source files for generic classes

Solution 1:

I think the common solution to this problem is to name the file like this:

{ClassName}`{NumberOfGenericParameters}

This would give you this filename:

Bag.cs and Bag`1.cs

This is the way Microsoft handle this issue in frameworks like Asp.net Mvc.

Solution 2:

I have seen some libraries using

Bag.cs
Bag`1.cs
Bag`2.cs

as this is what the Type.Name would display.

I want to be more descriptive with the type parameters so I lately tend to use

Bag.cs
Bag{T}.cs
Bag{TKey, TValue}.cs

This is a format that is also supported by the XML comments.

/// <summary>
/// ...
/// Uses the <see cref="T:MyLibrary.Bag{TKey, TValue}" /> class.
/// </summary>

Solution 3:

Usually if I have several types "overloaded" by the number of type parameters, it's either because one derives from the other or one is used to create the other. I just put them in the same file.

One alternative option would be to split them into different files, make one file the "primary" one, and the others "depend" on it in the build file, as per the partial class question you linked to in the question.

That way you could end up with a visual link in Visual Studio, but still one class per file to make it easier to work with them.

Solution 4:

In the CoreFX GitHub repository, Microsoft is following the back-tick convention described in Matthias Jakobsson's answer:

enter image description here

So basically:

class ImmutableArray { }                      // ImmutableArray.cs
class ImmutableArray<T> { }                   // ImmutableArray`1.cs
...
class ImmutableDictionary<TKey, TValue> { }   // ImmutableDictionary`2.cs

And for classes defined inside other classes, the name is composed by the outer class followed by + and by the name of the inner class (Outer+Inner.cs):

partial class ImmutableArray<T>               // ImmutableArray`1+Builder.cs
{
    class Builder { }
}