Click here to Skip to main content
15,918,617 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi ,

why is the declaration of enum must be outside main method ?
Posted

Because an enum is a basically a type; it has to be declared in a namespace, or in an enclosing class.
You cannot define types in methods.
 
Share this answer
 
Because you can't declare any type - class, struct or enum within a method: they are either local to the class / struct or global to the namespace. The language does not allow for classes, structs or enums to be local to a method.

It makes sense if you think about it - if you could, you would reduce the amount of scope you have to refactor your methods into separate functions: the "sub methods" could not access the enum declared within the body of the other method.
 
Share this answer
 
An Enum is a special "high-level" Type in C#; like Classes and Structs it can be defined either within a Namespace, or inside a Class or Struct. Enums in a Namespace are, then, available to all Classes, or Structs, in the Namespace.

Note, however, that you cannot define an Enum within a Struct; however, you can have a variable of Type Enum in a Struct.

You cannot define a Class, Enum, or Struct inside a method; that's just the way the C# language is implemented. You can think of an Enum as part of the declarative aspect of creating your Application structure, while you might think of Methods, and EventHandlers, as being part of the dynamic part of Application structure.

An Enum groups together a set of integral Types; you might think of an Enum as a ordered set of named Constants.

Good reading on Enums:

MSDN: [^].

C# Language Definition: download .pdf file from here: [^].

CodeProject: [^], and a wealth of CP resources here: [^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900