Convention for generic and non-generic types with same name
Asked Answered
T

2

7

Task is an example of a class that exists in generic and non-generic form. The generic form extends the non-generic form.

public class Task
{

}

public class Task<T> : Task
{

}

Say I was implementing something of the sort myself. Normally, the convention is to put different classes in different files. Since they have the same name, it is not possible here.

What is the convention for this sort of scenario? Keep both classes in the same file, or put the generic class in a different file, but with a different name?

Tidings answered 26/12, 2015 at 0:50 Comment(2)
FWIW, here's a similiar question: #3108689Carpospore
I normally put both classes in the same file. The reasoning is that one of them ends up being a wrapper around the other, and hence has minimal code.Berkley
B
8

Although Microsoft does not publish a standard way of dealing with this situation, they put Task<TResult> in a different file, with the name that is unrelated to Task: non-generic class is in the file Task.cs, while generic one is in the file Future.cs.

Similarly, Expression and Expression<TResult> are located in different files (Expression.cs and LambdaExpression.cs).

It appears that the logic behind placement of classes in files is that the class goes with other classes with which it logically belongs.

Boys answered 26/12, 2015 at 1:8 Comment(0)
L
3

The convention I've adopted (and subsequently encouraged at my workplace) is to add the generic parameters to the file name. So, for example, we'd have Task.cs for the non-generic version and Task(T).cs for the generic version. The reasoning behind this is largely due to us very strictly enforcing a one class per file rule.

Laureen answered 26/12, 2015 at 1:48 Comment(3)
So if you only have a generic version, do you still name it Task(T).cs?Tidings
@Tidings In general, no, although it'd probably make more sense if we did. Right now the rule only comes into play to disambiguate generic and non-generic classes with the same name.Laureen
Indeed, truth be told, it does feel a bit inconsistent to work that way.Tidings

© 2022 - 2024 — McMap. All rights reserved.