C# File Structure – Best Way to Name Files Containing Generic Classes

cnet

In my current project I have come across the requirement to create generic classes with the same name, but different numbers of generic parameters. For example:

MyClass<T1>
MyClass<T1, T2>
MyClass<T1, T2, T3>

Given that I want all of these in the same namespace, I am confused as to how to structure and name my classes and files?

If we follow the idea that we should have classes limited to one per file and that files should be in a folder structure that represents namespace hierarchy and that the name of the file should match the name of the class, how do I deal with this situation?

What I am really asking here is what should I name the file that contains MyClass<T1>, and what should I name the file that contains MyClass<T1, T2>? I am not asking what the names of the type parameters should be.

Best Answer

MyGenericClass`1.cs
MyGenericClass`2.cs
MyGenericClass`3.cs

And so on, where the number after the backtick is the number of generic type parameters. This convention is used by Microsoft.

Alternatively, you can use something like

MyGenericCollectionClass[TKey, TValue].cs

which preserves not only the number of generic type parameters, but also their specific names. Granted, it doesn't preserve the angle brackets, but we can't have everything in life we want, can we?