Why does a non-closing #region
causes a compiler error? After all, the region itself has absolutely no impact on the compiled code, right?
I believe it is because it is a preprocessor directive, but why is that? It isn't used like the other directives after all.
class Application
{
#region Whatever <- Causes an error.
static void Main(string[] c)
{
}
}
Why can't it be just ignored? Or is there a feature I don't know about the #region
that explains why it is compiled?
Edit : I get that this example doesn't compile because there's no corresponding #endregion
. But shouldn't it be treated as a missing closing tag in an xml comment? I mean, it has the same importance doesn't it?
Second edit: I'm looking to understand the design decision behind making #region
a preprocessor directive. Why not just a kind of comment that the IDE would recognize as a region of code that can be collapsed?
Why does a non-closing #region causes a compiler error?
Because the specs say so.
A #region block must be terminated with a #endregion directive.
Yes, they will not be part of the compiled program, but others pre-processor directives can define, what has to be part of program, for example #if DEBUG
(include something).
2.5 Pre-processing directives
Pre-processing directives are not tokens and are not part of the syntactic grammar of C#. However, pre-processing directives can be used to include or exclude sequences of tokens and can in that way affect the meaning of a C# program.
For your question:
But why is the preprocessor even considering the #region tag, why was it created as a preprocessor directive and not just another kind of comment?
regions are helpful for IDE (Visual Studio) purpose, it would be very hard (if not impossible) to achieve the same feature of collapsing/expanding code without regions. (this is my guess, only a member of Dev team from Microsoft could answer this)
Region directive:
No semantic meaning is attached to a region; regions are intended for use by the programmer or by automated tools to mark a section of source code. The message specified in a #region or #endregion directive likewise has no semantic meaning; it merely serves to identify the region. Matching #region and #endregion directives may have different pp-messages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With