C#9 supports top-level statements, but I am curious whether it is possible to apply any attribute to generated main method (STAThread
, actually), or I have to use classical approach with Main
method.
Asked
Active
Viewed 390 times
2

Pavel Anikhouski
- 21,776
- 12
- 51
- 66

Pavel Voronin
- 13,503
- 7
- 71
- 137
-
Do you mean you would like to use this feature in a WinForms app? – Jimi Mar 13 '21 at 17:34
-
Not necessary WF, but yes, I used it, but now I need to apply `[STAThread]`, so I switched back to defining main method explicitly. – Pavel Voronin Mar 13 '21 at 17:36
-
I've never used it, but my understanding was that this feature is meant for Console apps, to *ease the approach*. Or other more specific/targeted uses. I don't know what 's the *advantage* of it in a WinForms app. WPF already has it's own way of *hiding* Main. – Jimi Mar 13 '21 at 17:39
-
Does this answer your question? [How to handle {STAThread\] in C# 9 Using Top-Level Program.cs](https://stackoverflow.com/questions/64946371/how-to-handle-stathread-in-c-sharp-9-using-top-level-program-cs) – TnTinMn Mar 15 '21 at 01:11
-
@TnTinMn It's also an option, thanks for the idea. – Pavel Voronin Mar 15 '21 at 04:27
1 Answers
3
This feature was designed for newcomers to language so they won't need to write bunch of boilerplate each time. So this
namespace HelloWorldProg
{
public static class HelloWorldClass
{
public static void Main(string[] args)
{
System.Console.WriteLine("Finally I can write Hello World");
}
}
}
transforms to this
System.Console.WriteLine("That's much easier!");
It's a question of entry threshold and learning curve. Without top-level statement you need to know about
- namespaces
- classes
- incapsulation
- static/instance members
- passing arguments
- arrays
- how to write text to console
While with top-level statements you need to know only about last item to be able to write program and you may dig into other themes latter.
It's like "how to write 'hello world' in Haskell". Well, you need to know monads, IO in particular and do-notation. In order to know monads you should learn category theory.
Now answering your question: You cannot declare attributes with top-level statements. They were designed for different purposes. Proposal, priorities in platform design

JL0PD
- 3,698
- 2
- 15
- 23