[Proposal]: Flexible placement of module imports, static class imports, aliases (i.e. all using statements,) and file-scope namespace declarations. #8071
Unanswered
Kile-Asmussen
asked this question in
Language Ideas
Replies: 1 comment 3 replies
-
I just tried this with Java 8 and Java 21 IMO, directives that affect the scoping of types throughout the source file are the most important parts of that source file, and they should be front and center. Unlike Java, there is no direct relationship between a C# source file and any types declared within that file. The C# language and compiler do not share your opinion that a single class declaration is the most important part. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
TL;DR: It would massively improve ergonomics for reading code in non-IDE settings and obey principle of least surprise.
I don't think it is controversial to state that the most important part of any given C# code file is the class declaration.
I propose that the most important parts of a code file should be at the beginning of a file.
The import list is arguably among the least interesting parts of code files, and yet by the C# language specification we are forced to put it at the beginning. This means, if we view code as a form of prose, every single code file buries the lede, which is considered bad practice in prose writing. Also, every IDE worth its salt will hide the import list from view and automatically manage imports: it is not even important enough for most developers to directly look at 95% of the time.
(For other languages like Python and C, there are technical limitations forcing import lists to be at the beginning of the file, but C# is a modern compiled language with true modules.)
Import lists at the beginning of file also has practical consequences: the command-line utility
head
gives no insight at all into what a given code file defines and it means that opening a code file in a simple text editor always requires scrolling 10-20 lines down.C# 12, unlike Java, allows multiple top-level declarations in a code file.
using
-statements and file-scoped namespace declarations appear to be top-level declarations, but are in fact not. They are special things that must go at the beginning of the file, which violates the principle of least surprise.Furthermore Java actually allows end-of-file imports,while languages like Rust is extremely flexible with imports.(Regrettably, most Java IDEs still put imports at the top.)Forcing imports to be at the top of the file is, fundamentally, an aesthetic choice made by the language designers. There is no reason to enforce with compiler errors what should be a code style option.
Beta Was this translation helpful? Give feedback.
All reactions