Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One class per file rule in .NET? [closed]

Tags:

c#

.net

People also ask

Why one class per file?

Having one type per file has the following advantages: You can easily see which types changed in one particular commit, without doing diffs. It's easier the see the history of a type. You'll have more files, so the probability of having 2 or more people working on the same file will be lower.

Can you have multiple classes in one file C#?

This section provides a tutorial example on how to write multiple classes in a single C# source code file. Unlike Java, C# allows you to write multiple classes in a single source file.

Should each class have its own file C#?

While the one class per file policy is strictly enforced in Java, it's not required by C#. However, it's generally a good idea.

Can we have two classes in the same file?

Yes, it can. However, there can only be one public class per . java file, as public classes must have the same name as the source file. One Java file can consist of multiple classes with the restriction that only one of them can be public.


I hate it when people think in absolutes and say you should never do this or that with something subjective and nit-picky like this, as if we all need to conform to someones stupid idea of right and wrong. Bottom line: having more than one class per file is totally fine if it makes sense. By makes sense I mean things like:

  1. Makes the code easier to digest and maintain
  2. Makes the solution less annoying (scrolling through countless unnecessary files) and less slow
  3. The dev team is okay with it as a local coding practice

A really good example of why I may want multiple classes per file:

Say I've got a few dozen custom exception classes, each one is a 4 liner, I could have a separate file for each one or I could group the exceptions and have a file per group. For me what seems the most rational/pragmatic approach is to group them, and just have a few files, because it's more efficient time/coding wise (I don't have to right-click -> Add Class, rename, 50 times), it keeps the solution less cluttered and better performing.


One class per file also gives you a better idea of what each check in is changing without looking at the diffs of the file.


static bool GeneralRuleShouldBeFollowed(IGeneralRule rule, IUseCase useCase)
{
    return (rule.Overhead(useCase) 
            < My.PersonalThresholds.ConformismVsPracticality);
}

I sometimes group more than one class within a file if they are tightly coupled and at least one of them is very small.

General 'best practice' is to have one file per class.